多对多关系的jpa标准

我在Java中有2个POJO类,Answer和Colabor,在多对多的关系中。

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

类有一组 ,但 a 不保留一组 。我需要从Hibernate做的是找到合作者,以获得id给出的答案。AnswerCollaboratorCollaboratorAnswerCriteriaQuery

我已经使用结果转换器使用Hibernate()完成了此操作,但是在使用时我遇到了困难,因为我没有要为连接提供答案的列表。Criteriaorg.hibernate.CriteriaCriteriaQuery


答案 1

终于完成了...

代码如下:

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

答案 2

使用 HQL:

您可以使用以下命令:

Criteria criteria = session.createCriteria(Answer.class);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.createAlias("collaborators", "collaborators");
criteria.add(Restrictions.eq("collaborators.id",desiredCollaboratorId);

以获取与某个协作者关联的所有答案。

还有这个:

Criteria criteria = session.createCriteria(Answer.class);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.setFetchMode("collaborators", FetchMode.JOIN)
criteria.add(Restrictions.idEq(desiredAnswerId));
dsrTrackingCriteria.setProjection(Projections.property("collaborators"));

获取与某个答案关联的所有协作者。

使用 JPA2 Criteria API,您可以执行如下操作:

CriteriaBuilder cb = em.getCriteriaBuilder(); //creted from EntityManager instance

CriteriaQuery<Long> cq = cb.createQuery(Collaborator.class);
Root<Answer> rootAnswer = cq.from(Answer.class);
Join<Collaborator,Answer> joinAnswerCollaborator = rootAnswer.join("collaborators"); //(or rootAnswer.join(Answer_.collaborators); if you've created the metamodel with JPA2

推荐