hibernate 多对多关系的JPA标准

z3yyvxxp  于 2022-11-14  发布在  其他
关注(0)|答案(4)|浏览(146)

我在Java中有两个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找到合作者。
我已经使用结果转换器使用Hibernate Criteria(org.hibernate.Criteria)完成了这项工作,但是当涉及到使用CriteriaQuery时,我被卡住了,因为我没有可以给连接提供答案的列表。

uelo1irk

uelo1irk1#

终于完成了..。
代码如下:

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

disbfnqx2#

使用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
8hhllhi2

8hhllhi23#

使用Criteria Builder:

Join<CLASS_A, CLASS_B> join = root.join(WHAT_UVE_DECLARED_IN_MAPPEDBY, JoinType.INNER);
searchCriteria.add(criteriaBuilder.like(join.get("FIELD_IN_SUBCLASS").as(String.class), "%blabla%"));
hsgswve4

hsgswve44#

Join<Answer , Collaborator> join = root.join("collaborators",JoinType.INNER);

predicates.add(criteriaBuilder.equal(join.get("id"),id));

相关问题