我有这样的代码
@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_A
和Entity_B
是manyToMany
关联的实体:
Join<Entity_A, Entity_B> join = root.join("associationList", JoinType.INNER);
predicates.add(cb.like(join.get("name").as(String.class), "%test%"));
关于java - CriteriaBuilder选择ManyToMany,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45433003/