JPA动态查询--Spring Data Specification



例子使用Teacher类

Teacher{
String name;
String address;
String email;
}

1.使用MetaModel generator生成相应类的metaModelclass,工具有很多,可以使用maven,eclipse插件也行。得到Teacher_
2.新建一个继承Specification接口的类,重写toPredicate方法例如要根据Teacher name,address,email查询相应的教师信息。

public class TeacherSpec implements Specification {
private final Teacher teacher;
publicTeacherSpec(TeacherSpec teacher){
this.teacher= teacher;
}

@Override
public Predicate toPredicate(Root root, CriteriaQuery query,CriteriaBuilder cb) {
List=new ArrayList();
if(StringUtils.isNotBlank(teacher.getName())){
predicates.add(cb.equal(root.get(Teacher_.name),teacher.getName()));
}
if(StringUtils.isNotBlank(teacher.getAddress)){
predicates.add(cb.like(root.get(Teacher_.address),teacher.getAddress()+"%"));
}
if(StringUtil.isNotBlank(teacher.getEmail())){
predicates.add(cb.like(root.get(Teacher_.email),teacher.getEmail()+"%"));
}
returnandTogether(predicates,cb);
}

private PredicateandTogether(List predicates, CriteriaBuilder cb) {
return cb.and(predicates.toArray(newPredicate[0]));
}
}

3.Dao接口继承JpaRepository,JpaSpecificationExecutor

TeacherDao entends JpaRepository, JpaSpecificationExecutor**

4.Service方法中获得一个查询标准类TeacherSpec的对象,teacherSpc然后调用dao方法就好了

Page=teacherDao.findAll(teacherSpc,newPageRequest(pageNo,pageSize))**

你可能感兴趣的:(JPA动态查询--Spring Data Specification)