Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...