Spring Data JPA中如何优雅的构建动态查询语句

Spring Data JPA中如何优雅的构建动态查询语句

使用过Spring Data JPA的同学们应该都清楚,Spring Data JPA很好的简化了我们持久层的开发,但是实际应用中,我们经常需要动态查询。目前常用的动态查询构建方式为:Criteria API、Dao层接口实现JpaSpecificationExecutor两种,但是无论是哪一种,构建多条件查询的时候都需要if-else构建多个Predicate对象来进行条件查询,下面讲给大家分享一个github上的第三方库:https://github.com/wenhao/jpa-spec,供大家参考。

三方库引入方式:

Gradle

repositories {
jcenter()
}
dependencies {
compile 'com.github.wenhao:jpa-spec:3.2.3'
}

Maven


com.github.wenhao
jpa-spec
3.2.3


动态查询构建例子:

Dao层继承两个父类:JpaRepository、JpaSpecificationExecutor

public interface PersonRepository extends JpaRepository, JpaSpecificationExecutor {
}

动态查询构建代码

public Page findAll(SearchRequest request) {
Specification specification = Specifications.and()
.eq(StringUtils.isNotBlank(request.getName()), "name", request.getName())
.gt(Objects.nonNull(request.getAge()), "age", 18)
.between("birthday", new Date(), new Date())
.like("nickName", "%og%", "%me")
.build();
return personRepository.findAll(specification, new PageRequest(0, 15));
}

Equal/NotEqual使用范例:

public List findAll(SearchRequest request) {
Specification specification = Specifications.
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 findAll(SearchRequest request) {
Specification specification = Specifications.and()
.like("name", "%ac%")
.predicate(Specifications.or()
.lt("age", 19)
.gt("age", 25)
.build())
.build();
return personRepository.findAll(specification);
}

更多范例,大家可以移步github地址查看文档,这个真的很给力有木有,不需要重复的构建Predicate对象,不需要重复的if-else语句,让我们也知道,写代码也是可以很优雅的。


分享到:


相關文章: