SpringDataJPA 动态查询,JpaSpecificationExecutor 快速条件构造工具类

版权声明:本文为博主原创文章转载请附上原文出处链接。

依赖自定义utils如下 Json、NotNullHandle,话不多书,上代码.

使用实例

    JpaQuery<Product> jpaQuery = specificationHelper ->
                specificationHelper.equal("productCategoryId", productCategoryId)
                        .equal("loadCategoryId", loadCategoryId)
                        .lessThanOrEqualTo("maxLoan", maxLoan)
                        .greaterThanOrEqualTo("minLoan", minLoan)
                        .and();

        Page<Product> data = domainRepository.findAll(jpaQuery, PageUtils.create(limit, page, Sort.by(Sort.Direction.DESC, "sort")));
      

使用实例2

    /**
     * 
     * @param jsonObject 参数
     * @param page 
     * @param limit
     */

    public void test(JSONObject jsonObject,Integer page, Integer limit) {
       Pageable pageable = PageUtils.create(limit, page, Sort.by(Sort.Direction.DESC, "sort"));
        Page<Product> data =  domainRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                SpecificationHelper.newInstance(root, criteriaQuery, criteriaBuilder, Json.newInstance(jsonObject)).
                        equal("productCategoryId")
                        .equal("loadCategoryId")
                        .lessThanOrEqualTo("maxLoan")
                        .greaterThanOrEqualTo("minLoan")
                        .and(),pageable);
    }

Specification 接口实现类

/**
 * @param <T>
 * @author itzgyw
 * @describe Specification 实现类
 */
public interface JpaQuery<T> extends Specification<T> {

    Predicate helper(SpecificationHelper<T> specificationHelper);

    @Override
    default Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        return this.helper(SpecificationHelper.newInstance(root, criteriaQuery, criteriaBuilder));
    }
}

以下是具体实现


/**
 * @param <T>
 * @author itzgyw
 * @describe 条件构造工具
 */

public class SpecificationHelper<T> {


    private Root root;
    private CriteriaQuery criteriaQuery;
    private CriteriaBuilder criteriaBuilder;
    private List<Predicate> predicateList;
    private Json json;

    private SpecificationHelper(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder, Json json) {
        this.root = root;
        this.json = json;
        this.criteriaQuery = criteriaQuery;
        this.criteriaBuilder = criteriaBuilder;
        this.predicateList = new ArrayList<>();
    }

    public static SpecificationHelper newInstance(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
        return new SpecificationHelper(root, criteriaQuery, criteriaBuilder, null);
    }

    public static SpecificationHelper newInstance(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder, Json json) {
        return new SpecificationHelper(root, criteriaQuery, criteriaBuilder, json);
    }

    public SpecificationHelper<T> equal(String key, Object val) {
        NotNullHandle.execute(key, val, (k, v) -> predicateList.add(criteriaBuilder.equal(this.get(k), v)));
        return this;
    }

    public SpecificationHelper<T> equal(String key) {
        this.equal(key, getJson().get(key));
        return this;
    }

    public SpecificationHelper<T> leftLike(String key, Object val) {
        NotNullHandle.execute(key, val, (k, v) -> predicateList.add(criteriaBuilder.like(this.get(k), "%" + v.toString())));
        return this;
    }

    public SpecificationHelper<T> leftLike(String key) {
        this.leftLike(key, getJson().get(key));
        return this;
    }

    public SpecificationHelper<T> rightLike(String key, Object val) {
        NotNullHandle.execute(key, val, (k, v) -> predicateList.add(criteriaBuilder.like(this.get(k), v.toString() + "%")));
        return this;
    }

    public SpecificationHelper<T> rightLike(String key) {
        this.rightLike(key, getJson().get(key));
        return this;
    }

    public SpecificationHelper<T> like(String key, Object val) {
        NotNullHandle.execute(key, val, (k, v) -> predicateList.add(criteriaBuilder.like(this.get(k), "%" + v.toString() + "%")));
        return this;
    }

    public SpecificationHelper<T> like(String key) {
        this.like(key, getJson().get(key));
        return this;
    }

    public SpecificationHelper<T> between(String key, String val, String val2) {
        NotNullHandle.execute(key, val, val2, (k, v, v2) -> predicateList.add(criteriaBuilder.between(this.get(k), v, v2)));
        return this;
    }

    public SpecificationHelper<T> between(String key) {
        getJson().acceptIfExist(key, this, (k, v, _this) -> {
            String[] vArray = v.toString().split("~");
            if (vArray.length != 2) {
                return;
            }
            _this.between(k, vArray[0], vArray[1]);
        });
        return this;
    }

    public SpecificationHelper<T> greaterThan(String key, Object val) {
        NotNullHandle.execute(key, val, (k, v) -> predicateList.add(criteriaBuilder.greaterThan(this.get(k), v.toString())));
        return this;
    }

    public SpecificationHelper<T> greaterThan(String key) {
        this.greaterThan(key, getJson().get(key));
        return this;
    }

    public SpecificationHelper<T> lessThan(String key, Object val) {
        NotNullHandle.execute(key, val, (k, v) -> predicateList.add(criteriaBuilder.lessThan(this.get(k), v.toString())));
        return this;
    }

    public SpecificationHelper<T> lessThan(String key) {
        this.lessThan(key, getJson().get(key));
        return this;
    }

    public SpecificationHelper<T> tisLessThan(String key, String key2) {
        NotNullHandle.execute(key, key2, (k, k2) -> predicateList.add(criteriaBuilder.lessThan(this.get(k), this.get(k2))));
        return this;
    }

    public SpecificationHelper<T> greaterThanOrEqualTo(String key, Object val) {
        NotNullHandle.execute(key, val, (k, v) -> predicateList.add(criteriaBuilder.greaterThanOrEqualTo(this.get(k), v.toString())));
        return this;
    }

    public SpecificationHelper<T> greaterThanOrEqualTo(String key) {
        this.greaterThanOrEqualTo(key, getJson().get(key));
        return this;
    }

    public SpecificationHelper<T> lessThanOrEqualTo(String key, Object val) {
        NotNullHandle.execute(key, val, (k, v) -> predicateList.add(criteriaBuilder.lessThanOrEqualTo(this.get(k), v.toString())));
        return this;
    }


    public SpecificationHelper<T> tisLessThanOrEqualTo(String key, String key2) {
        NotNullHandle.execute(key, key2, (k, k2) -> predicateList.add(criteriaBuilder.lessThanOrEqualTo(this.get(k), this.get(k2))));
        return this;
    }

    public SpecificationHelper<T> lessThanOrEqualTo(String key) {
        this.lessThanOrEqualTo(key, getJson().get(key));
        return this;
    }

    public Predicate and() {
        Predicate predicate = criteriaBuilder.and(this.predicateList.toArray(new Predicate[this.predicateList.size()]));
        this.predicateList.clear();
        return predicate;
    }

    public Predicate or() {
        Predicate predicate = criteriaBuilder.or(this.predicateList.toArray(new Predicate[this.predicateList.size()]));
        this.predicateList.clear();
        return predicate;
    }


    private Path get(String key) {
        return root.get(key);
    }

    private Json getJson() {
        if (this.json == null) {
            throw new RuntimeException("SpecificationHelper.getJson is null ");
        }
        return this.json;
    }


}

自定义工具类Json

public class Json {

    private JSONObject meta;


    private Json(JSONObject jsonObject) {
        this.meta = jsonObject;
    }

    public static Json newInstance(JSONObject jsonObject) {
        Assert.notNull(jsonObject, " parameter jsonObject is null !!");
        return new Json(jsonObject);
    }

    public Json computeIfAbsent(String key, Function<Object, Object> function) {
        this.meta.computeIfAbsent(key, function);
        return this;
    }


    public <V, C> Json acceptIfExist(String key, C pc, JpaConsumer<String, V, C> consumer) {
        V val = (V) this.meta.get(key);
        if (val == null) {
            return this;
        }
        consumer.accept(key, val, pc);
        return this;
    }

    public Object get(String key) {
        return this.meta.get(key);
    }

}

自定义工具类NotNullHandle

public class NotNullHandle {

    public static <T> void execute(T t, Consumer<T> consumer) {
        if (t != null) {
            consumer.accept(t);
        }
    }

    public static <T, V> void execute(T t, V v, BiConsumer<T, V> consumer) {
        if (t != null && v != null) {
            consumer.accept(t, v);
        }
    }

    public static <T, V, C> void execute(T t, V v, C c, JpaConsumer<T, V, C> consumer) {
        if (t != null && v != null && c != null) {
            consumer.accept(t, v, c);
        }
    }

    public static <T, V> V executeF(T t, Function<T, V> function) {
        if (t != null) {
            return function.apply(t);
        }
        return null;
    }
}

自定义函数接口 JpaConsumer

@FunctionalInterface
public interface JpaConsumer<T,V,C> {
    void accept(T t,V v,C c);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值