封装查询代码
Specification<TsUser> spec = new Specification<TsUser>() {
@Override
public Predicate toPredicate(Root<TsUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Criteria<TsUser> c = new Criteria<TsUser>();
c.add(Restrictions.like("userName", userSearch.getUserName()));// UserSearch是前端封装的查询表单对象
c.add(Restrictions.between("createdAt", DateUtil.parse(costSearch.getDateFrom()), DateUtil.parse(costSearch.getDateTo())));//区间查询
c.add(Restrictions.like("tsUserreg.userAlias", userSearch.getUserAlias()));//查询其他相关表字段
c.add(Restrictions.eq("status", userSearch.getStatus()));// 精确查询
return c.toPredicate(root, query, cb);
}
};
Restrictions.java片段
public static SimpleExpression eq(String fieldName, Object value) {
if(StringUtils.isEmpty(value))return null;
return new SimpleExpression (fieldName, value, Operator.EQ);
}
public static BetweenExpression between(String fieldName, Object value, Object value2) {
if(StringUtils.isEmpty(value) && StringUtils.isEmpty(value2)) return null;
return new BetweenExpression(fieldName, value, value2);
}
AbstractExpression,计算查询路径(支持属性嵌套,例如address.zipCode)
public abstract class AbstractExpression implements Criterion {
Path getExpression(Root<?> root, String fieldName) {
Path expression = null;
if(fieldName.contains(".")){
String[] names = StringUtils.split(fieldName, ".");
expression = root.get(names[0]);
for (int i = 1; i < names.length; i++) {
expression = expression.get(names[i]);
}
}else{ expression = root.get(fieldName); }
return expression;
}
}
SimpleExpression,支持Equal、Like、LessThan等条件
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
Path expression = getExpression(root, fieldName);
switch (operator) {
case EQ:
return builder.equal(expression, value);
case LIKE:
return builder.like((Expression<String>) expression, "%" + value + "%");
}
}
BetweenExpression,支持区间查询
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
Path expression = getExpression(root, fieldName);
if(StringUtils.isEmpty(value)) {
return builder.greaterThanOrEqualTo(expression, (Comparable)value);
}else if(StringUtils.isEmpty(value2)) {
return builder.lessThanOrEqualTo(expression, (Comparable)value2);
}else {
return builder.between(expression, (Comparable)value, (Comparable)value2);
}
}
Criteria,
public class Criteria<T> implements Specification<T>{
private List<Criterion> criterions = new ArrayList<Criterion>();
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (!criterions.isEmpty()) {
List<Predicate> predicates = new ArrayList<Predicate>();
for(Criterion c : criterions){
predicates.add(c.toPredicate(root, query,builder));
}
// 将所有条件用 and 联合起来
if (predicates.size() > 0) {
return builder.and(predicates.toArray(new Predicate[predicates.size()]));
}
}
return builder.conjunction(); // 没有条件时相当于true
}
public void add(Criterion criterion){
if(criterion!=null){
criterions.add(criterion);
}
}
}