CriteriaBuilder选择ManyToMany

时间:2017-08-01 08:44:02

标签: java jpa predicate

我有这样的代码

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
public Registration getRegistration() {
    return registration;
}

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "COMPANY_USER", joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "COMPANY_ID", referencedColumnName = "ID"))

public List<CompanyInfo> getCompanyInfoList() {
    return companyInfoList;
}

对于注册中的例子(@OneToOne),我搜索

private Predicate[] buildPredicates(UserFilter example, CriteriaBuilder qb, Root root) {
    ArrayList<Predicate> predicates = new ArrayList<>();
    if (example != null) {
    predicates.add(qb.like(qb.upper(root.get(UserInfo_.registration).get(Registration_.messageCode)), "%TEST%"));
    }
    return predicates.toArray(new Predicate[predicates.size()]);
}

如何正确搜索List CompanyInfo(@ManyToMany)

predicates.add(qb.like(qb.upper(root.get(UserInfo_.companyInfoList).... ??

例如我想得到这样的sql

SELECT u.id, u.login_name, c.name
  FROM user_info  u
       INNER JOIN company_user cu ON cu.user_id = u.id
       INNER JOIN company_info c ON cu.company_id = c.id
 WHERE UPPER (c.name) LIKE 'ОДО%'

company_user是链接表。

使用CriteriaBuilder

    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<Long> query = qb.createQuery(Long.class);
    Root<UserInfo> root = query.from(UserInfo.class);
    query.select(qb.count(root.get(UserInfo_.id)));

    Subquery<String> subquery = query.subquery(String.class);
    Root<CompanyInfo> subRoot = subquery.from(CompanyInfo.class);
    subquery.select(subRoot.get(CompanyInfo_.id));

    List<Predicate> restrictions = buildPredicates(example, qb, root);
    List<Predicate> restrictionsSub = buildPredicatesSub(example, qb, subRoot);
    Predicate[] predicates = joinList(restrictions, restrictionsSub);
    query.where(predicates);

    return em.createQuery(query.distinct(true)).getSingleResult();

1 个答案:

答案 0 :(得分:1)

试试这个,Entity_AEntity_BmanyToMany相关实体:

Join<Entity_A, Entity_B> join = root.join("associationList", JoinType.INNER);
predicates.add(cb.like(join.get("name").as(String.class), "%test%"));