简单条件查询
我们可以通过定义在Repository接口在的方法名称来执行查询等操作,以find,get,read开头,涉及条件查询时,Spring Data JPA支持将条件属性定义在数据访问层接口下,首字母需要大写
比如:
findByName 等同于JPQL语句:select s from student s where s.name = ?1
因此,可以直接通过在数据访问层定义方法名称即可进行数据的访问操作
find可以换成count、delete、get等等
关键字 | 示例 | 同功能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 | findByAgeIsNull | 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> age) | 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) |
关联查询和@Query查询
对于两个有关联关系的对象的查询,可以通过方法名中的"_"下划线来标识,同时也直接用@Query注解定义在数据访问层接口的方法上实现查询。
比如:stu和clazz两个关联的对象
通过方法名中的"_"下划线来标识
通过@Query注解
测试成功:
通过@NamedQuery:
NamedQuery语句应该放到要查询的实体上,并且名称是“实体类名.方法名”