JPA的查询方法总结

一、使用where条件
上一篇我们使用JPA进行了数据源的访问,默认JPA已经实现了好几个接口可以调用。但是,在实际的业务中,查询语句不可避免地需要使用where、order by等语句。

我们用商品数据来做例子,添加一个价格字段price,按价格范围查询,看看怎么来实现。

方式一:通过方法名称来实现
public interface GoodsRepository extends JpaRepository<Goods, Long> {
List<Goods> findByPriceBetween(Double startPrice, Double endPrice);
}
Spring Data JPA 查询方法支持的关键字(可参考:https://docs.spring.io/spring-data/jpa/docs/2.2.x/reference/html/#repositories.query-methods)

Table 2.2. Supported keywords inside method names

方式二:通过自定义SQL来实现
在现实中,可能会含有非常复杂的SQL语句,或者为了性能优化,我们需要自定义sql。JPA提供注解和XML配置这2中方式。

public interface GoodsRepository extends JpaRepository<Goods, Long> {
@Query(value = "select * from goods g where g.price between :startPrice and :endPrice", nativeQuery = true)
List<Goods> findByPriceBetween(Double startPrice, Double endPrice);
}
二、order by查询
使用order by也可以编写在方法名上,可以把以上例子改为

public interface GoodsRepository extends JpaRepository<Goods, Long> {
List<Goods> findByPriceBetweenOrderByPriceAsc(Double startPrice, Double endPrice);

————————————————
版权声明:本文为CSDN博主「loophome」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/loophome/article/details/87186778

猜你喜欢

转载自www.cnblogs.com/fengli9998/p/11904265.html