前言
最近看springBoot中小例子时,看到了spring Data JPA,就简单了解一下。
什么是Spring Data JPA?
JPA即Java Persistence API.JPA是一个基于O/R映射的标准规范。所谓规范即只定义标准规则(如注解、接口),不提供实现,软件提供商可以按照标准规范来实现,而使用者只需按照规范中的定义的方式来使用,而不用和供应商的实现打交道。JPA的主要实现由Hibernate、EclipeLink和OpenJPA等,意味着我们只要使用JPA来开发,无论哪一个开发方式都是一样的。
是Spring Data的一个子项目,通过提供基于JPA的Repository极大地减少了作为数据访问方案的代码量。
查询关键字
关键字 | 示例 | 同功能JPQL |
And | findByLastnameAndFirstname | where x.lastname=?1 and x.firstname=?2 |
Or | findByLastnameOrFirstname | where x.lastname=?1 or x.firstname=?2 |
IsEquals | 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> ages) | where x.age not in ?1 |
True | findByActiveTrue() | where x.active = true |
False | findByActiveFalse() | where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | where UPPER(x.firstname)=UPPER(?1) |
小结
望名知意,可以简化代码量,其实还有很多特性。