spring-boot:使用JPA访问数据源(二)实现where条件,order by查询

上一篇文章:spring-boot:使用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

KeywordSampleJPQL snippet
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
BetweenfindByStartDateBetween… where x.startDate between 1? and ?2
LessThanfindByAgeLessThan… where x.age < ?1
GreaterThanfindByAgeGreaterThan… where x.age > ?1
AfterfindByStartDateAfter… where x.startDate > ?1
BeforefindByStartDateBefore… where x.startDate < ?1
IsNullfindByAgeIsNull… where x.age is null
IsNotNull,NotNullfindByAge(Is)NotNull… where x.age not null
LikefindByFirstnameLike… where x.firstname like ?1
NotLikefindByFirstnameNotLike… where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith… where x.firstname like ?1 (parameter bound with appended %)
EndingWithfindByFirstnameEndingWith… where x.firstname like ?1 (parameter bound with prepended %)
ContainingfindByFirstnameContaining… where x.firstname like ?1 (parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot… where x.lastname <> ?1
InfindByAgeIn(Collection<Age> ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection<Age> age)… where x.age not in ?1
TruefindByActiveTrue()… where x.active = true
FalsefindByActiveFalse()… where x.active = false

 

方式二:通过自定义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);
}

至于自定义sql这里就省略了


版权声明:本文为loophome原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。