如何将自定义派生查询POST添加到spring数据REST?

时间:2016-07-19 03:17:19

标签: spring spring-data-rest

我有一个我正在学习的Spring数据REST项目。

现在我想在此存储库中设置查询:

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends PagingAndSortingRepository<User, Long>

即,这家伙:

    @RestResource(path = "login", rel = "login")
    User findByUsernameAndPassword(String username, String password);

基本存储库很容易设置。自定义GET请求也是如此:

List<Item> findByType(@Param("type") String type);

@RestResource(path = "byMaxPrice")
@Query("SELECT i FROM Item i WHERE i.price <= :maxPrice")
List<Item> findItemsLessThan(@Param("maxPrice") double maxPrice);

但这些仍然是GET请求。我想使用POST请求。 method = RequestMapping.POST不接受@RestResource标记..我在文档中没有看到任何提及不同的请求类型。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您需要定义自定义Controller来处理POST请求。如果你只是想为默认的Repository方法做POST,遗憾的是,你仍然需要通过Controller

@RepositoryRestController
public class MyController implements Serializable {

...
@RequestMapping(value = "/myConstroller/myPostMethod", method = RequestMethod.POST
     , consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.OK)
public @ResponseBody List<MyObjects>  updateMyObjectList(
    @RequestBody List<MyObjects> objects) { 
    // Call your repository method here, or a custom service, or whatever
}

有关详细信息,请参阅Spring MVC docs,特别是5.2.1部分,其中介绍了对存储库的默认HTTP方法支持,以及16.4,它提供了自定义控制器示例。

从5.2.1开始:

  

POST

     

从给定的请求主体创建一个新实体。

因此,支持POST,但不支持您尝试执行的操作。如果你想&#34;隐藏&#34;使用POST而不是GET的URL参数,您需要一个自定义控制器。