查询方法,就是根据方法名来检索数据。按照一定的规则,通过方法名描述要检索的字段,过滤的条件,排序的策略等等,它们大都以find
, get
… 等开头。spring-data-jpa会自动解析,并且完成检索。省时省力。
在 Repository 中定义查询方法
public interface UserRepository extends Repository<User, Long> {
// 根据emailAddress和lastname 检索所有的记录
List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);
}
这个方法最终执行的JPQL
select u from User u where u.emailAddress = ?1 and u.lastname = ?2
支持的语法
关键字 | 例如 | 最终执行的JPQL 片段 |
---|---|---|
And |
findByLastnameAndFirstname |
… where x.lastname = ?1 and x.firstname = ?2 |
Or |
findByLastnameOrFirstname |
… where x.lastname = ?1 or x.firstname = ?2 |
Is , Equals |
findByFirstname , findByFirstnameIs , findByFirstnameEquals |
… where x.firstname = ?1 |
Between |
findByStartDateBetween |
… where x.startDate between ?1 and ?2 |
LessThan |
findByAgeLessThan |
… where x.age < ?1 |
LessThanEqual |
findByAgeLessThanEqual |
… where x.age <= ?1 |
GreaterThan |
findByAgeGreaterThan |
… where x.age > ?1 |
GreaterThanEqual |
findByAgeGreaterThanEqual |
… where x.age >= ?1 |
After |
findByStartDateAfter |
… where x.startDate > ?1 |
Before |
findByStartDateBefore |
… where x.startDate < ?1 |
IsNull , Null |
findByAge(Is)Null |
… where x.age is null |
IsNotNull , NotNull |
findByAge(Is)NotNull |
… where x.age not null |
Like |
findByFirstnameLike |
… where x.firstname like ?1 |
NotLike |
findByFirstnameNotLike |
… where x.firstname not like ?1 |
StartingWith |
findByFirstnameStartingWith |
… where x.firstname like ?1 (需要自己对字符串参数添加: % ) |
EndingWith |
findByFirstnameEndingWith |
… where x.firstname like ?1 (需要自己对字符串参数添加: % ) |
Containing |
findByFirstnameContaining |
… where x.firstname like ?1 (需要自己对字符串参数添加: % ) |
OrderBy |
findByAgeOrderByLastnameDesc |
… where x.age = ?1 order by x.lastname desc |
Not |
findByLastnameNot |
… where x.lastname <> ?1 |
In |
findByAgeIn(Collection<Age> ages) |
… where x.age in ?1 |
NotIn |
findByAgeNotIn(Collection<Age> ages) |
… where x.age not in ?1 |
True |
findByActiveTrue() |
… where x.active = true |
False |
findByActiveFalse() |
… where x.active = false |
IgnoreCase |
findByFirstnameIgnoreCase |
… where UPPER(x.firstame) = UPPER(?1) |
使用到
In
和NotIn
等对集合进行计算关键的字方法,支持使用Collection
子类,或者数组作为参数的形参。
支持对象属性导航
class User {
// User对象关联了一个Address 对象
Address address;
}
class Address {
String name;
}
public interface UserRepositroy extends JpaRepository<User, Integer>{
// 从address属性导航到它的name属性
findByAddressName(String name);
// 更为科学的写法, 通过下户线标识遍历的节点
findByAddress_Name(String name);
}
JPA里面, 下户线是保留标识符,但是下划线又破话了Java的驼峰规则
分页和排序
只需要在方法的最后一个参数定义: Sort
/ Pageable
对象,即可自动的完成排序/分页
Sort
和Pageable
是JPA定义用来排序和分页的对象
也可以通过 First/Top 方法名限制结果集
findFirst10ByName(String name);
findTop10ByName(String name);
以上2个方法,都表示根据 name
属性检索前10条记录
官方文档
这个花样确实多,不过用到的就那么几个,有兴趣,可以阅读官方文档系统学习
https://docs.spring.io/spring-data/jpa/docs/current-SNAPSHOT/reference/html/#jpa.query-methods