使用 spring 规范查询过滤集合 [英] Query filtering a collection using spring specifications

查看:32
本文介绍了使用 spring 规范查询过滤集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体 A(ManyToMany、direct、lazy),它持有对实体 B 集合的引用.

I have an entity A (ManyToMany, direct, lazy) which holds a reference to a collection of entities B.

我需要查询数据库,根据它引用的 B 类元素搜索实体 A.我如何使用 Spring 规范来做到这一点?

I need to query the DB, searching for entities A based on the elements of class B it references. How can I do that with Spring specifications?

推荐答案

你可以这样做:

@Entity
public class A{

@ManyToMany
@JoinTable(....)
private Set<B> bs;
// getters and Setters

}

B 类,假设您想通过比较 b.property 进行查询

Class B , let's suppose you want to query by comparing a b.property

@Entity
public class B{
@Column
private String property;
// getters and setters 
}

提供规范的抽象类:

public abstract class ASpecifications{
    public static Specification<A> findByProperty(final String prop) {
        return new Specification<A>() {

            @Override
            public Predicate toPredicate(Root<A> root,
                    CriteriaQuery<?> arg1, CriteriaBuilder cb) {
                return cb.equal(root.join(A_.bs).get(B_.property), prop);
            }
        };
    }
}

现在@服务层这样使用:

Now use it @ the service layer this way :

import static package.ASpecifications.*;
import static org.springframework.data.jpa.domain.Specifications.where;

@Transactional(...)
public List<A> findByJoinPropertyOFB(String prop){
Specifications<A> spec = where(findByProperty(prop));
retrun repository.findAll(spec);
}

现在确保你的 Repository 扩展了 JpaSpecificationExecutor

Now make sure that your Repository extends JpaSpecificationExecutor<A>

如果 B 包含对另一个对象的引用 C 并且您想比较抛出 C 的值

If B Contains a reference To another Object C and you want to compare throw a value of C

规范可以这样扩展:

cb.equal(root.join(A_.bs).get(B_c).get(c_.property), prop);

B_ , C_A_ 是实体的元模型.希望这会有所帮助.

B_ , C_ And A_ are MetaModels of your entities. Hope this will help.

这篇关于使用 spring 规范查询过滤集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆