JPA中Specification方法
@Repository
public interface ProjectDao extends JpaRepository<Project, String> {
Page<Project> findAll(Specification<Project> specification,Pageable pageable);
}
- 步骤二:复写Specification方法,将查询条件条件到 criteriaBuilder中。
public class ProjectDaoSpec {
public static Specification<Project> getVariableSpec( String projectName, String leaderId
){
return (entity, query, criteriaBuilder) -> {
Predicate predicate = criteriaBuilder.isFalse(entity.get("isDeleted"));
List<Predicate> additionList = new ArrayList<>();
if (!StringUtil.isNullOrEmpty(projectName))
{
additionList.add(criteriaBuilder.like(entity.get("projectName"), "%" + projectName + "%"));
}
if (!StringUtil.isNullOrEmpty(leaderId))
{
additionList.add(criteriaBuilder.equal(entity.get("leaderId"), leaderId));
}
for (Predicate addition : additionList) {
predicate = criteriaBuilder.and(predicate, addition);
}
return predicate;
};
}
}
- 步骤三:在service中,调用分页查询,并转换为Dto。
public PageData<ProjectDto> getPage(
String projectName,
String leaderId
Pageable pageRequest) {
Specification<Project> specification = ProjectDaoSpec.getVariableSpec(projectName,leaderId);
return getProject(projectDao.findAll(specification, pageRequest));
}