jpa criteria for many to many relationship

user998692 picture user998692 · Nov 15, 2011 · Viewed 25.4k times · Source

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.

Answer

user998692 picture user998692 · Nov 18, 2011

It's done, finally...

Here's the code:

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

    }