java - hibernate/jpa criteria, query if an object exists in a many to many relation -
i have class offer
many 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 use jpa criteriabuilder
search offer
objects contain department
(namedcode
).
this should part of greater query (see 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 offer object has assigned passed department } // add more restrictions criteria.orderby(builder.asc(root.get("entrydate")));
i figured out, have use join after all:
restrictions.add(builder.equal(root.join("department").get("id"), department.getid()));
Comments
Post a Comment