列表中的列表。条件 API

List in list. Criteria API

我有两个实体:

实体:

@Entity
@Data
public class AEntity{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

}

B实体:

@Entity
@Data
public class BEntity{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @ManyToMany(fetch = FetchType.EAGER)
    private List<AEntity> aEntities = new LinkedList();
}

我想通过 aEntities 从数据库加载所有 BEntities,其中包含使用标准 API.

的 AEntity 名称列表

示例:

Database:
AEntities -> {1, "A1"}, {2, "A2"}, {3, "A3"}
BEntities -> {1, AEntities: {1, 2, 3}}, {2, AEntities: {1, 3}}, {3, AEntities: {3}}

如果我调用 mySearchMethod(List.of("A1", "A3")) 它应该 return: {1, AEntities: {1, 2, 3}}, {2, AEntities: {1, 3}} 因为只有这些 BEntities 包含名称为“A1”和“A3”的 AEntities

试图用 in 表达式实现它,但它无法在列表中找到列表:(

我还没有尝试过,但它可能会这样工作:

public List<BEntity> mySearchMethod(List<String> keyList){
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<BEntity> cq = cb.createQuery(BEntity.class);
    Root<BEntity> r = cq.from(BEntity.class);
        
    cq.select(r);
    ArrayList<Predicate> predicates = new ArrayList<>();
    for(String key : keyList) {
        predicates.add(cb.isMember(key, r.get(BEntity_.aEntities)));
    }
    if(predicates.size() > 0) {
        if(predicates.size() == 1) {
            cq.where(predicates.get(0));
        }else {
            cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
        }
    }
    TypedQuery<BEntity> query = em.createQuery(cq);

    return query.getResultList();
}