使用Spring Dat JPA,我需要查询我的数据库并OrderEntity基于数量的astartAmt和a返回一个s范围endAmt。我不确定是否应该将这两个变量映射到entity OrderEntity,作为某种类型的单独类/实体/模型中的字段,还是直接在本机查询中声明它们。也许我应该使用实现的服务EntityManager.createNativeQuery()?
OrderEntity
startAmt
endAmt
EntityManager.createNativeQuery()
想做类似的事情:
@Repository public interface OrderRangeRepository extends JpaRepository<OrderEntity, OrderEntityID> { @Query(value = "SELECT * FROM Orders WHERE Amount BETWEEN startAmt AND endAmt;" , nativeQuery=true) List<OrderEntity> findOrdersBy(int startAmt, int endAmt); }
如果要EntityManager.createNativeQuery()在服务中使用,则可能类似于以下内容:
@Service public class OrderRangeService { @Autowired EntityManager entityManager; public List<OrderEntity> findAmountsBetween() { List<OrderEntity> amountsBetween = entityManager.createNativeQuery("SELECT * FROM Orders WHERE Amount BETWEEN ?1 AND 2?;") .setParameter(1, "startAmt") .setParameter(2, "endAmt") .getResultList(); return amountsBetween; } }
您可以使用Spring Data JPA实现此目的,而无需定义本机查询。
@Repository public interface OrderRangeRepository extends JpaRepository<OrderEntity, OrderEntityID> { List<OrderEntity> findByAmountBetween(int startAmt, int endAmt); }
如果要使用本机查询,请将其更改为
@Query(value = "SELECT * FROM Orders WHERE Amount BETWEEN :startAmt AND :endAmt" , nativeQuery=true) List<OrderEntity> findOrdersBy(@Param("startAmt") int startAmt, @Param("endAmt") int endAmt);
您可以通过以下方式在服务中调用查询:
@Service public class OrderRangeService { @Autowired OrderRangeRepository orderRangeRepository ; public List<OrderEntity> findAmountsBetween(int startAmt, int endAmt) { List<OrderEntity> amountsBetween = orderRangeRepository.findByAmountBetween(startAmt, endAmt); return amountsBetween; } }
最后,您应该从控制器中自动连接OrderRangeService并调用findAmountsBetween服务方法
@Autowired OrderRangeService orderRangeService; @GetMapping("/amountsFromAndTo") @ResponseBody public String getAmounts(@RequestParam int startAmt, @RequestParam int endAmt) { List<OrderEntity> orderEntityL = orderRangeService.findAmountsBetween(startAmt, endAmt); return orderEntityL.toString(); }