Spring Data JPA - 参考文档 4.3。查询方法

4.3。查询方法

4.3.1。查询查询策略

JPA模块支持以String形式手动定义查询,或者从方法名称派生它。

声明的查询

尽管获取从方法名派生的查询非常方便,但可能会遇到这样的情况,即方法名解析器不支持要使用的关键字,或者方法名称会不必要地变得难看。所以,你可以通过命名约定使用JPA命名查询(请参阅使用JPA NamedQueries获取更多信息)或相当具有注解你的查询方法@Query(请参阅使用@Query了解详细信息)。

4.3.2。查询创建

通常,JPA的查询创建机制按查询方法中的描述工作以下是JPA查询方法转化为的一个简短示例:

示例45.从方法名称创建查询
公共接口UserRepository扩展了Repository <User,Long> {

  List <User> findByEmailAddressAndLastname(String emailAddress,String lastname);
}

我们将使用JPA标准API从此创建一个查询,但本质上这转换为以下查询:select u from User u where u.emailAddress = ?1 and u.lastname = ?2Spring Data JPA将执行属性检查并遍历属性表达式中所述的嵌套属性以下是对JPA支持的关键字的概述,以及包含该关键字本质的翻译方法。

表4.方法名称中支持的关键字
关键词 样品 JPQL片段

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstnamefindByFirstnameIsfindByFirstnameEquals

… 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> 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还可以接受任何Collectionas参数的子类以及数组或可变参数。对于逻辑运算符相同的其他语法版本,请检查存储库查询关键字

猜你喜欢

转载自blog.csdn.net/daqiang012/article/details/80207160