Spring Data JPA 查询规范

按照 Spring Data 的规范,查询方法以 findBy | readBy | getBy 开头

//例如:定义一个 Entity 实体类
class User{ 
    private String firstName; 
    private String lastName; 
}

//使用And条件连接时,应这样写:
findByLastNameAndFirstName(String lastName,String firstName);
//条件的属性名称与个数要与参数的位置与个数一一对应

直接在接口中定义查询方法,如果是符合规范的,可以不用写实现,目前支持的关键字写法如下:

关键字 简单示例 JPQL片段示例
AND findByLastNameAndFirstName WHERE Entity.lastName = ?1 AND Entity.firstName = ?2
OR readByLastNameOrFirstName WHERE Entity.lastName = ?1 OR Entity.firstName = ?2
Between getByStartDateBetween WHERE Entity.startDate BETWEEN ?1 AND ?2
LessThan findByAgeLessThan WHERE Entity.age < ?1
GreaterThan readByAgeGreaterThan WHERE Entity.age > ?1
After只作用在时间 findByStartDateAfter WHERE Entity.startDate > ?1
Before只作用在时间 findByStartDateBefore WHERE Entity.startDate < ?1
LessThanEqual findByAgeLessThenEqual WHERE Entity.age <= ?1
GreaterThanEqual readByAgeGreaterThenEqual WHERE Entity.age >= ?1
Is findByLastNameIs WHERE Entity.lastName = ?1
Equal getByFirstNameEqual WHERE Entity.firstName = ?1
IsNull findByAddressIsNull WHERE Entity.address is NULL
IsNotNull readByAddressIsNotNull WHERE Entity.address NOT NULL
NotNull readByAddressNotNull WHERE Entity.address NOT NULL
Like findByNameLike WHERE Entity.name LIKE ? 不包括’%’符号
Not Like findByNameNotLike WHERE Entity.name not like ?1 不包括’%’符号
StartingWith readByNameStartingWith WHERE Entity.name like ‘?1%’条件以’%’符号结尾
EndingWith readByName EndingWith WHERE Entity.name like ‘%?1’条件以’%’符号开头
Containing getByNameContaining WHERE Entity.name like ‘%?1%’ 包含’%’符号
OrderBy findByAgeOrderByAddressDesc WHERE Entity.age = ? Order By Entity.address DESC
Not readByAgeNot WHERE Entity.age <> ?1 不等于
In findByNameIn(Collection name) WHERE Entity.name IN (?1 ,?2, ?3)
NotIn getByNameNotIn(Collection name) WHERE Entity.name NOT IN (?1 ,?2, ?3)
True readByFloagTrue() WHERE Entity.floag = true
False readByFloagFalse() WHERE Entity.floag = false
IgnoreCase findByNameIgnoreCase WHERE UPPER(Entity.Name) = UPPER(?1)

本文由创作和发表,采用 CC BY 3.0CN协议进行许可,转载请注明作者及出处。本文作者, 原文标题为Spring Data JPA 查询关键词对照表。原文链接为:https://www.ramostear.com/post/2018/10/22/54.html

评论区

是技术也是艺术