gpt4 book ai didi

java - hibernate/jpa 标准,查询对象是否存在于多对多关系中

转载 作者:行者123 更新时间:2023-11-30 02:47:50 25 4
gpt4 key购买 nike

我有一个类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 搜索包含特定 department (NamedCode) 的所有 Offer 对象)。

这应该是更大查询的一部分(请参阅 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")));

最佳答案

我明白了,毕竟我必须使用连接:

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

关于java - hibernate/jpa 标准,查询对象是否存在于多对多关系中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39638565/

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