我在
Java,Answer和Collaborator中有两个POJO类,多对多关系.
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); }
类答案有一套Collaborator,但是Collaborator不保留一组答案.
从Hibernate CriteriaQuery中我需要做的是找到由id给出的答案的协作者.
我已经使用结果变量使用了Hibernate Criteria(org.hibernate.Criteria),但是当我使用CriteriaQuery时,我并没有提供给这个join的答案列表.
解决方法
完成了,终于…
以下是代码:
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(); }