我在Java中有2个POJO类,Answer和Collaborator,具有多对多关系。
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); }
类Answer有一套Collaborator,但Collaborator没有一套Answer。我需要在Hibernate中进行的工作CriteriaQuery是找到合作者,以获得id给出的答案。
Answer
Collaborator
CriteriaQuery
我已经使用结果转换器使用Hibernate Criteria(org.hibernate.Criteria)进行了此操作,但是在使用时我陷入了困境CriteriaQuery,因为我没有要提供给联接的答案列表。
Criteria
org.hibernate.Criteria
完成了,终于…
这是代码:
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(); }