使用过Spring Data JPA的同学们应该都清楚,Spring Data JPA很好的简化了我们持久层的开发,但是实际应用中,我们经常需要动态查询。目前常用的动态查询构建方式为:Criteria API、Dao层接口实现JpaSpecificationExecutor
三方库引入方式:
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 PagefindAll(SearchRequest request) {
Specificationspecification = 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 ListfindAll(SearchRequest request) {
Specificationspecification = 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 ListfindAll(SearchRequest request) {
Specificationspecification = Specifications. and()
.like("name", "%ac%")
.predicate(Specifications.or()
.lt("age", 19)
.gt("age", 25)
.build())
.build();
return personRepository.findAll(specification);
}
更多范例,大家可以移步github地址查看文档,这个真的很给力有木有,不需要重复的构建Predicate对象,不需要重复的if-else语句,让我们也知道,写代码也是可以很优雅的。
閱讀更多 技術小白stabber 的文章