使用spring规范查询过滤集合

Ste*_*ola 0 spring-data

我有一个实体A(ManyToMany,direct,lazy),其中包含对实体B集合的引用。

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

Raf*_*LDI 5

好吧,你可以这样做:

@Entity
public class A{

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

}
Run Code Online (Sandbox Code Playgroud)

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

@Entity
public class B{
@Column
private String property;
// getters and setters 
}
Run Code Online (Sandbox Code Playgroud)

提供规范的抽象类:

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);
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

现在以这种方式在服务层中使用它:

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);
}
Run Code Online (Sandbox Code Playgroud)

现在确保您的存储库已扩展 JpaSpecificationExecutor<A>

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

可以通过以下方式扩展规范:

cb.equal(root.join(A_.bs).get(B_c).get(c_.property), prop);
Run Code Online (Sandbox Code Playgroud)

B_C_而且A_是你的实体的元模型。希望这会有所帮助。