46 SpringDataJpa Specification接口用法

原文链接:https://blog.csdn.net/bird_tp/article/details/83654789
Specification是springDateJpa中的一个接口,用于当jpa的一些基本CRUD操作的扩展,即spring jpa的复杂查询接口。Criteria 查询,是一种类型安全和更面向对象的查询。而Spring Data JPA支持JPA2.0的Criteria查询,相应的接口是JpaSpecificationExecutor。
Specification接口中只定义了如下一个方法:

Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb); 

先简单了解JPA2.0的Criteria查询:
Criteria 查询是以元模型的概念为基础的,元模型是为具体持久化单元的受管实体定义的,这些实体可以是实体类,嵌入类或者映射的父类。

CriteriaQuery接口:代表一个specific的顶层查询对象,它包含着查询的各个部分,比如:select 、from、where、group by、order by等注意:CriteriaQuery对象只对实体类型或嵌入式类型的Criteria查询起作用。

Root接口:代表Criteria查询的根对象,Criteria查询的查询根定义了实体类型,能为将来导航获得想要的结果,它与SQL查询中的FROM子句类似。
1:Root实例是类型化的,且定义了查询的FROM子句中能够出现的类型。root代表查询的实体类,query可以从中得到root对象,告诉jpa查询哪一个实体类,还可以添加查询条件,还可以结合EntityManager对象 得到最终查询的 TypedQuery对象.

2:查询根实例能通过传入一个实体类型给 AbstractQuery.from方法获得。

3:Criteria查询,可以有多个查询根。

4.CriteriaBuilder接口:用来构建CritiaQuery的构建器对象Predicate:一个简单或复杂的谓词类型,其实就相当于条件或者是条件组合。

使用:
单表查询

List<SUser> sUserList = sUserDao.findAll((root, query, cb) -> {
    //root.get("username")表示获取username这个字段名称,like表示执行like查询,%zt%表示值
    Predicate p1 = cb.like(root.get("username"), "%zt%");
    Predicate p2 = cb.greaterThan(root.get("id"), 3);
    //将两个查询条件联合起来之后返回Predicate对象,username模糊查询,id>3
    return cb.and(p1, p2);
});
//select * from s_user where (id = 2 or id = 3) and (email like 'zt%' or username like 'foo%')
//第一个Specification定义了两个or的组合
Specification<SUser> s1 = (root, query, cb) -> {
    Predicate p1 = cb.equal(root.get("id"), 2);
    Predicate p2 = cb.equal(root.get("id"), 3);
    return cb.or(p1, p2);
};

//第二个Specification定义了两个or的组合
Specification<SUser> s2 = (root, query, cb) -> {
    Predicate p1 = cb.like(root.get("email"), "kk%");
    Predicate p2 = cb.like(root.get("username"), "foo%");
    return cb.or(p1, p2);
};
        
//通过Specifications将两个Specification连接起来,第一个条件加where,第二个是and
List<SUser> sUserList = sUserDao.findAll(Specifications.where(s1).and(s2));

多表查询

/**
 * 构建查询条件 三张表内联查询实例
 *
 * @param categoryId 分类id
 * @param name       商品名称
 * @param shopId     店铺id
 * @return 查询条件
 */
public Specification<ProductGroup> buildProductGroupSpec(Integer shopId, String name, Integer categoryId, Integer shopKindId, Boolean health) {
    return (root, query, cb) -> {
        Join<ProductGroup, Shop> shopJoin = root.join("shop", JoinType.INNER);
        Join<Shop, ShopDatum> shopDatumJoin = shopJoin.join("shopDatum", JoinType.INNER);
        Join<Shop, ShopConfig> shopConfigJoin = shopJoin.join("shopConfig", JoinType.INNER);
        List<Predicate> predicates = Lists.newArrayList();
        if (shopId != null) {
            predicates.add(cb.equal(root.get("shop"), shopId));
        }
        if (StringUtils.isNotEmpty(name)) {
            predicates.add(cb.like(root.get("name"), "%" + name.trim() + "%"));
        }
        if (categoryId != null) {
            predicates.add(cb.equal(root.get("category"), categoryId));
        }
        if (shopKindId != null && shopKindId != 0) {
            predicates.add(cb.like(root.get("shopKindIds"), "," + shopKindId + ","));
        }
        predicates.add(cb.equal(root.get("auditState"), AUDIT_STATE_YES.getKey()));
        predicates.add(cb.equal(root.get("offline"), Boolean.FALSE));
        predicates.add(cb.greaterThanOrEqualTo(shopDatumJoin.get("openShopExpire"), new Date()));
        predicates.add(cb.equal(shopConfigJoin.get("openShop"), Boolean.TRUE));
        Predicate p1 = cb.equal(root.get("health"), Boolean.FALSE);
        Predicate p2 = cb.equal(root.get("health"), Boolean.TRUE);
        Predicate p3 = cb.greaterThanOrEqualTo(shopDatumJoin.get("openHealthShopExpire"), new Date());
        if (health == null) {
            predicates.add(cb.or(p1, cb.and(p2, p3)));
        }
        if (health != null) {
            if (health) {
                predicates.add(cb.and(p2, p3));
            } else {
                predicates.add(cb.and(p1));
            }
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
//两张表内联,排序我的是
Specification<User> spec = (root, query, cb) -> {
    Join<User, UserAsset> userJoin = root.join("userAsset", JoinType.INNER);
    List<Predicate> predicates = Lists.newArrayList();
    predicates.add(cb.gt(userJoin.get("wpoint"), 0));
    cb.and(predicates.toArray(new Predicate[predicates.size()]));
    query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    query.orderBy(cb.desc(userJoin.get("wpoint")));
    return query.getRestriction();
};
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值