jpa 动态查询条件 数组_JPA使用Specification构建动态查询

本文介绍了如何利用Spring Data JPA的Specification接口构建动态查询条件,包括单条件和多条件查询,并展示了and、or操作的用法,适用于处理复杂的数据库查询需求。
摘要由CSDN通过智能技术生成

封装Specification查询条件,在Spring Data JPA 2.0以前使用 Specifications 这个辅助类来操作where、not、and和or连接,在2.0版本以后这个类会被剔除,可以直接使用 Specification 自身对象来操作where多条件连接。(以下展示单表多条件查询)

import org.springframework.data.jpa.domain.Specification;

import org.springframework.data.jpa.domain.Specifications;

import javax.persistence.criteria.*;

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

/**

* SQL拼接工具类

*

* @author yanhu

* @date 2018/8/9

*/

public class SpecificationFactory {

private Specifications specs;

private SpecificationFactory(Specification specs) {

this.specs = Specifications.where(specs);

}

public static SpecificationFactory wheres(Specification spec) {

return new SpecificationFactory(spec);

}

public SpecificationFactory and(Specification other) {

this.specs.and(other);

return this;

}

public SpecificationFactory or(Specification other) {

this.specs.or(other);

return this;

}

public Specifications build() {

return this.specs;

}

/**

* 单where条件

*

* @param p

* @return

*/

public static Specification where(Predication p) {

List ps = new ArrayList<>();

ps.add(p);

return where(ps);

}

/**

* 多where条件and连接

*

* @param ps

* @param

* @return

*/

public static Specification where(List ps) {

return (Root root, CriteriaQuery> query, CriteriaBuilder builder) ->

builder.and(getPredicateList(root, builder, ps));

}

/**

* 多where条件or连接

*

* @param ps

* @param

* @return

*/

public static Specificat

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值