Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
441 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...