Spring Boot JPA自定义查询(新手必看)
JPA 除了可以直接使用 JpaRepository 接口提供的基础功能外,还支持根据实体的某个属性实现数据库操作,Spring Data JPA 能够根据其方法名为其自动生成 SQL,支持的关键字有 find、query、get、read、count、delete 等,主要的语法是 findByXX、queryByXX、getByXX、readByXX、countByXX 等。
利用这个功能,仅需要在定义的 Repository 中添加对应的方法名即可,无须具体实现,使用时 Spring Data JPA 会自动根据方法名来生成 SQL 语句。
这个语句结构可以使用下表说明:
按照 Spring Data 的规范,查询方法以 find、read、get 开头。涉及查询条件时,条件的属性用条件关键字进行连接。需要注意的是,条件属性首字母大写。
利用这个功能,仅需要在定义的 Repository 中添加对应的方法名即可,无须具体实现,使用时 Spring Data JPA 会自动根据方法名来生成 SQL 语句。
JPA属性查询
如果想根据实体的 name 属性来查询 User 的信息,那么直接在 UserRepository 中增加一个接口声明即可:User findByUserName(String userName);从上面的示例可以看到,我们可以在 UserRepository 接口中声明 findByUserName 方法,无须实现,JPA 会自动生成对应的实现方法及其 SQL 语句。
JPA组合查询
JPA 不仅支持单个属性查询,还支持多个属性查询,根据 And、Or 等关键字进行组合查询,示例代码如下:User findByNameOrPassword (String name,String password);在上面的示例中,根据姓名和密码两个属性组合查询,属性名称与个数要与参数的位置与个数一一对应。这是组合查询的例子,删除与统计也是类似的,如 deleteByXXXAndXXX、countByXXXAndXXX。可以根据查询的条件不断地添加和拼接,Spring Data JPA 都可以正确解析和执行。
JPA关键字进行自定义查询
JPA 的自定义查询除了 And、Or 关键字外,基本上 SQL 语法中的关键字 JPA 都支持,比如 like、between 等。这个语句结构可以使用下表说明:
关键字 | 示例方法 | JPQL 语句 |
---|---|---|
And | findByLastnameAndFirstname | ... where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | ... where x.lastname = ?1 or x.firstname = ?2 |
Is,Equals | findByFirstname,findByFirstnames,findByFirstnameEquals | ... where x.firstname = ?1 |
Between | findByStartDateBetween | ... where x.startDate between ?1 and ?2 |
LessThan | findByAgeLessThan | ... where x.age < ?1 |
LessThanEqual | findByAgeLessThanOrEqualTo | ... where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | ... where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanOrEqualTo | ... 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(isNotNull) | ... where x.age not null |
Like | findByFirstnameLike | ... where x.firstname like '%1' |
NotLike | findByFirstnameNotLike | ... where x.firstname not like '%1' |
StartingWith | findByFirstnamesStartingWith | ... where x.firstname like '%1' (parameter bound with appended %) |
EndingWith | findByFirstnamesEndingWith | ... where x.firstname like '%1' (parameter bound with prepended %) |
Containing | findByFirstnameContaining | ... where x.firstname like '%1' (parameter bound wrapped in %) |
OrderBy | findByAgeOrderBy | ... where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | ... where x.lastname <> ?1 |
In | findByAgeIn | ... where x.age in ?1 |
NotIn | findByAgeNotIn | ... where x.age not in ?1 |
True | findByActiveTrue | ... where x.active = true |
False | findByFalse | ... where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | ... where UPPER(x.firstname) = UPPER(?1) |
按照 Spring Data 的规范,查询方法以 find、read、get 开头。涉及查询条件时,条件的属性用条件关键字进行连接。需要注意的是,条件属性首字母大写。