我的班级Offer
有多对多关系department
:
class Offer {
@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.MERGE, CascadeType.REFRESH })
@JoinTable(name = "Offer_Department", joinColumns = @JoinColumn(name = "offer_id"), inverseJoinColumns = @JoinColumn(name = "namecode_id"))
private Set<NamedCode> department;
...
}
如何使用JPA CriteriaBuilder
搜索包含特定Offer
(department
)的所有NamedCode
个对象。
这应该是更大查询的一部分(参见TODO部分):
CriteriaBuilder builder = getSession().getCriteriaBuilder();
CriteriaQuery<Offer> criteria = builder.createQuery(Offer.class);
Root<Offer> root = criteria.from(Offer.class);
List<Predicate> restrictions = new ArrayList<>();
if (fromDate != null && toDate != null) {
restrictions.add(builder.between(root.get("entryDate"), fromDate, toDate));
}
if (department != null) {
// TODO check if the Offer object has assigned the passed department
}
// add more restrictions
criteria.orderBy(builder.asc(root.get("entryDate")));
答案 0 :(得分:1)
我想通了,毕竟我必须使用连接:
restrictions.add(builder.equal(root.join("department").get("id"), department.getId()));