Reputation: 8100
I have an class Offer
with a many to many relation 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;
...
}
How can I use the JPA CriteriaBuilder
to search all Offer
objects which contain a certain department
(NamedCode
).
This should be part of a greater query (see the TODO part):
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")));
Upvotes: 2
Views: 1769
Reputation: 8100
I figured it out, I have to use a join after all:
restrictions.add(builder.equal(root.join("department").get("id"), department.getId()));
Upvotes: 2