我的端到端流程如下所示: 控制器->适配器->持久性/存储库-> DB
在我的控制器中:
@RequestMapping(value = "/userOrder/{orderID}", method = RequestMethod.DELETE)
public Set<?> deleteOrder(@PathVariable("orderID") String orderID) {
/*
* orderHandlerAdapter cancels the order and passed list of orders created + cancelled so * far.
*/
Set<Orders> orderList = orderHandlerAdapter.cancelOrder(orderID);
return orderList;
}
在适配器中:
public Set<Order> cancelOrder(String orderID) {
/*
* Cancel order first.
*/
userOrderRepository.saveOrder(orderID,"CANCELLED");
/*
* Return list of orders created and cancelled so far.
*/
Set<Order> orderList = userOrderRepository.getFirstByOrderIdAndStatusCdIsIn(orderID, new Set<String> {"CREATED","CANCELLED"});
return Set<Order>;
}
持续存在:
public interface orderRespository extends CrudRepository<UserOrder,String>() {
/*
* Save status = CANCELLED into the DB.
*/
void saveOrder(String orderID);
/*
* Get orders that are created and cancelled.
*/
Set<Order> getFirstByOrderIdAndStatusCdIsIn(String orderID, new Set<String> orderStatusSet);
}
我发现,当调用saveOrder / getFirstByOrderIdAndStatusCdIsInis时,查询未在任何地方定义,并且接口也未实现。但是结果可以正确返回。
这是如何工作的? JPA是否足够智能,可以根据方法名称创建查询?
答案 0 :(得分:1)
Spring Data has a default implementation for the methods from the repositories included in the product (CrudRepository
, PagingAndSortingRepository
, JpaRepository
, QueryByExampleExecutor
). You can find many in the SimpleJpaRepository
.
But it is not just that an instance of SimpleJpaRepository
gets added to the ApplicationContext
. instead, a proxy is used. The proxy checks the method being called and decides how to provide an implementation:
@Query
annotation or does its name match a named query -> call thatBeyond that Spring Data takes care of conversions between results of the queries and the required return type of the method.