Search code examples
javahibernatemany-to-manyjpa-2.0criteria

jpa criteria for many to many relationship


I have 2 POJO classes in Java, Answer and Collaborator, in a many-to-many relationship.

class Answer {
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "ANSWERS_COLLABORATORS", joinColumns = { @JoinColumn(name = "aid") }, inverseJoinColumns = { @JoinColumn(name = "cid") })
    private Set<Collaborator> collaborators = new HashSet<Collaborator>(0);
} 

Class Answer has a set of Collaborator, but a Collaborator doesn't keep a set of Answer. What I need to do from Hibernate CriteriaQuery is to find the collaborators for an answer given by id.

I have already done this with Hibernate Criteria (org.hibernate.Criteria) using result transformer, but I'm stuck when it comes to using CriteriaQuery, because I don't have a list of answers to give to the join.


Solution

  • It's done, finally...

    Here's the code:

    public List<Collaborator> getCollaborators(Long answerId) {
      CriteriaBuilder cb = entityManager.getCriteriaBuilder();
      CriteriaQuery<Collaborator> criteriaQuery = cb.createQuery(Collaborator.class);
      
      Root<Answer> answerRoot = criteriaQuery.from(Answer.class);
      SetJoin<Answer, Collaborator> answers = answerRoot.join(Answer_.collaborators);
      criteriaQuery.where(cb.equal(answerRoot.get(Answer_.id), answerId));
      
      return entityManager
        .createQuery(criteriaQuery.select(answers))
        .getResultList();
    }