Spring龍源國際客服DataI8669I44449JPA
三方庫引入方式:
Gradle
repositories {
jcenter()
}
dependencies {
compile ‘com.github.wenhao:jpa-spec:3.2.3‘
Maven
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.2.3</version>
</dependency>
動態查詢構建例子:
Dao層繼承兩個父類:JpaRepository、JpaSpecificationExecutor
public interface PersonRepository extends JpaRepository<Person, Long>, JpaSpecificationExecutor<Person> {
動態查詢構建代碼
public Page<Person> findAll(SearchRequest request) {
Specification<Person> specification = Specifications.<Person>and()
.eq(StringUtils.isNotBlank(request.getName()), "name", request.getName())
.gt(Objects.nonNull(request.getAge()), "age", 18)
.between("birthday", new Date(), new Date())
.build();
return personRepository.findAll(specification, new PageRequest(0, 15));
}
Equal/NotEqual使用範例:
public List<Person> findAll(SearchRequest request) {
Specification<Person> specification = Specifications.<Person>and()
.eq("nickName", "dog")
.eq(StringUtils.isNotBlank(request.getName()), "name", "Jack", "Eric", null)
.eq("company", null) //or eq("company", (Object) null)
.build();
return personRepository.findAll(specification);
}
同時使用And和Or語句構建範例:
public List<Person> findAll(SearchRequest request) {
Specification<Person> specification = Specifications.<Person>and()
.like("name", "%ac%")
.predicate(Specifications.or()
.lt("age", 19)
.gt("age", 25)
.build())
.build();
return personRepository.findAll(specification);
}
更多範例,大家可以移步github地址查看文檔,這個真的很給力有木有,不需要重復的構建Predicate對象,不需要重復的if-else語句,讓我們也知道,寫代碼也是可以很優雅的。
Spring龍源國際客服DataI8669I44449JPA