使用@PathVariable 获取多个请求参数

278*_*184 0 java spring-data spring-data-jpa spring-boot

在获取请求中使用多个参数调用请求时出现以下错误: http://localhost:8080/find/1/empid/146220

白标错误页面

此应用程序没有明确的 /error 映射,因此您将其视为后备。

Tue Aug 01 19:33:35 IST 2017 出现意外错误(类型 = 内部服务器错误,状态 = 500)。参数绑定的名称不能为 null 或为空!在 JDK < 8 上,您需要使用 @Param 来命名参数,在 JDK 8 或更高版本上,请务必使用 -parameters 进行编译。嵌套异常是 java.lang.IllegalArgumentException:参数绑定的名称不能为 null 或为空!在 JDK < 8 上,您需要使用 @Param 作为命名参数,在 JDK 8 或更高版本上,请务必使用 -parameters 进行编译。

演示.java

@Entity
public class Demo {

    @Id
    private Long id;
    private String name;
    private String value;
    //getter -setter
}
Run Code Online (Sandbox Code Playgroud)

演示应用程序.java

@SpringBootApplication
@RestController
public class DemoApplication {

    @Autowired
    private DemoRepository repository;

    @RequestMapping(method=RequestMethod.GET, value="/find/{id}/{name}/{value}")
    public Demo find(@PathVariable Long id, @PathVariable String name, @PathVariable String value){
        return repository.findByIdAndNameAndValue(id, name, value);
    }
}
Run Code Online (Sandbox Code Playgroud)

DemoRepository.java

public interface DemoRepository extends CrudRepository<Demo, Long>{

    @Query("select d from Demo d where d.id = :id and d.name = :name and d.value = :value")
    Demo findByIdAndNameAndValue(Long id, String name, String value);

}   
Run Code Online (Sandbox Code Playgroud)

Kyl*_*son 5

您需要指定PathVariable名称。

例子:

@RequestMapping(method=RequestMethod.GET, value="/find/{id}/{name}/{value}")
public Demo find(@PathVariable(name = "id") Long id, @PathVariable(name = "name") String name, @PathVariable(name = "value") String value){
    return repository.findByIdAndNameAndValue(id, name, value);
}
Run Code Online (Sandbox Code Playgroud)

在你的Query方法中也是如此

例子:

@Query("select d from Demo d where d.id = :id and d.name = :name and d.value = :value")
Demo findByIdAndNameAndValue(@Param("id") Long id, @Param("name") String name, @Param("value") String value);
Run Code Online (Sandbox Code Playgroud)