背景:
假设我们有一个数据表叫Person,有ID(Number)、NAME(Varchar2)、AGE(Number)、ADDRESS(Varchar2)几个字段;对应的实体类叫Person,分别有id(long),name(String),age(Integer),address(String)。
1. 根据属性名查询
Spring Data jpa 支持通过定义在Repository接口中的方法名来定义查询,而方法名时根据实体类的属性名来确定的。
- 常规查询。根据属性名来定义查询的方法,示例如下:
public interface PersonRepository extends JpaRepository<Person,Long> {
/**
* 通过名字相等查询,参数为name
* 相当于JPQL:select p from Person p where p.name = ?1
*/
List<Person> findByName(String name);
/**
*
* 通过名字like查询,参数为name
* 相当于JPQL:select p from Person p where p.name like ?1
*/
List<Person> findByNameLike(String name);
/**
*
* 通过名字和地址查询,参数为name 和 address
* 相当于JPQL:select p from Person p where p.name=?1 and p.address=?2
*
*/
List<Person> findByNameAndAddress(String name,String address);
}
从代码中看出,这里使用了findBy、Like、And这样的关键字。其中findBy可以用find、read、readBy、query、queryBy、get、getBy来代替。
而Like和and这类查询关键字,说明如下表:
关键字 | 示例 | 同功能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 | findByAgeGreaterEqual | 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 | findByAges(Is)NotNull | where x.age not null |
Like | findByFirstnameLike | where x.firstname like ?! |
NotLike | findByFirstnameNotLike | where x.firstname not like |