hibernate / jpa条件,查询对象是否存在多对多关系

时间:2016-09-22 12:04:21

标签: java hibernate jpa criteria hibernate-criteria

我的班级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搜索包含特定Offerdepartment)的所有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")));

1 个答案:

答案 0 :(得分:1)

我想通了,毕竟我必须使用连接:

restrictions.add(builder.equal(root.join("department").get("id"), department.getId()));