SpringDataJpA复杂查询实现自定义排序
作者:互联网
需求:
列表页面实现按合同状态自定义排序
private Specification<TblContractPre> whereClause(final TblContractPre entity) {
return new Specification<TblContractPre>() {
@Override
public Predicate toPredicate(Root<TblContractPre> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
if (entity.getId() != null) {
list.add(cb.equal(root.get("id").as(Long.class), entity.getId()));
}
if ("1".equals(entity.getFrom())) {
UserObject user = UserObjectHelper.currentUserObject();
List<String> ids = DataUtil.findAuditByCurUser(user, WorkflowType.HB_CONTRACT_ONLINE);
if (ids.isEmpty()) {
list.add(root.get("id").as(Long.class).in(0));
} else {
list.add(root.get("id").as(Long.class).in(UtilPublic.strArrToListLong(ids.toArray(new String[] {}))));
}
}
if (StringUtils.isNotBlank(entity.getHouseName())) {
list.add(cb.like(root.get("houseName").as(String.class), "%" + entity.getHouseName() + "%"));
}
if (StringUtils.isNotBlank(entity.getDeedsn())) {
list.add(cb.equal(root.get("deedsn").as(String.class), entity.getDeedsn()));
}
if (entity.getDeptId() != null) {
list.add(root.get("deptId").as(Integer.class).in(DataUtil.findSubDeptIds(entity.getDeptId())));
}
if (StringUtils.isNotBlank(entity.getSalesmanName())) {
list.add(cb.equal(root.get("salesmanName").as(String.class), entity.getSalesmanName()));
}
UserObject user = UserObjectHelper.currentUserObject();
if (user != null) {
if (user.isSales()) {
list.add(cb.equal(root.get("salesmanName").as(String.class), user.getUserCode()));
} else if (user.isBus()) {
list.add(root.get("deptId").as(Integer.class).in(user.getDeptIdList()));
}
}
if (entity.getContractStatus() != null) {
list.add(cb.equal(root.get("contractStatus").as(Byte.class), entity.getContractStatus()));
}
if (StringUtils.isNotBlank(entity.getDateType())) {
if (entity.getDeedsnStart() != null) {
list.add(cb.greaterThanOrEqualTo(root.get(entity.getDateType()).as(Date.class), entity.getDeedsnStart()));
}
if (entity.getDeedsnEnd() != null) {
list.add(cb.lessThanOrEqualTo(root.get(entity.getDateType()).as(Date.class), entity.getDeedsnEnd()));
}
}
if (entity.getCompanyType() != null) {
list.add(cb.equal(root.get("companyType").as(CompanyType.class), entity.getCompanyType()));
}
List<Order> orders = new ArrayList<>();
orders.add(cb.asc(cb.selectCase().when(cb.equal(root.get("contractStatus").as(Byte.class), 2), 1)
.when(cb.equal(root.get("contractStatus").as(Byte.class), 4), 2)
.when(cb.equal(root.get("contractStatus").as(Byte.class), 1), 3)
.when(cb.equal(root.get("contractStatus").as(Byte.class), 3), 4).otherwise(10)));
orders.add(cb.desc(root.get("createDate")));
query.orderBy(orders);
Predicate[] p = new Predicate[list.size()];
return query.where(cb.and(list.toArray(p))).getGroupRestriction();
}
};
}
标签:SpringDataJpA,自定义,get,cb,list,entity,排序,root,class 来源: https://blog.51cto.com/u_11710338/2845967