Spring Data JPA从CrudRepository实现过来的方法不是只有以下这几个的,如下:
public interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S var1);
<S extends T> Iterable<S> saveAll(Iterable<S> var1);
Optional<T> findById(ID var1);
boolean existsById(ID var1);
Iterable<T> findAll();
Iterable<T> findAllById(Iterable<ID> var1);
long count();
void deleteById(ID var1);
void delete(T var1);
void deleteAll(Iterable<? extends T> var1);
void deleteAll();
}
CrudRepository除了以上这几个,我们也可以自己根据Spring Data JPA提供的几种规则来构建适合于自己项目的查询语句,例如下面这个查询方法就是上方CrudRepository所没有的:
public interface UserRepository extends CrudRepository<User, Long> {
//这是一条AND查询语句,findBy为默认
List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);
}
那为什么这样写也能从数据库中读取到数据呢?
这是因为只要我们的Spring Data JPA查询语句遵循下面这些规则,它就能从数据库中读取到你所希望的数据:
Spring Data JPA查询关键字的规则简介:Keyword | Sample | SQL Example |
---|
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
| findByAgeGreaterThanEqual
| … where x.age >= ?1
|
After
| findByStartDateAfter
| … where x.startDate > ?1
|
Before
| findByStartDateBefore
| … where x.startDate < ?1
|
IsNull , Null
| findByAge(Is)Null
| … 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
(parameter bound with appended % ) |
EndingWith
| findByFirstnameEndingWith
| … where x.firstname like ?1
(parameter bound with prepended % ) |
Containing
| findByFirstnameContaining
| … where x.firstname like ?1
(parameter bound wrapped in % ) |
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)
|
上面的Spring Data JPA查询语句规则非常重要,了解了这些,你就能少些很多不必要的代码了。
其中findBy是默认的,必须得有,然后就是关键字keywords,关键字和findBy前后的都为参数,使用驼峰命名规则。
小编只是做为笔记记录下来,希望能帮助大家了解Spring JPA。
来源网站:太平洋学习网,转载请注明出处:http://www.tpyyes.com/a/javaweb/992.html