gpt4 book ai didi

java - CriteriaBuilder 选择多对多

转载 作者:行者123 更新时间:2023-12-02 12:26:38 26 4
gpt4 key购买 nike

我有这样的代码

@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()]);
}

以及如何在列表 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();

最佳答案

试试这个,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%"));

关于java - CriteriaBuilder 选择多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45433003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com