我在Java,Answer和Collaborator中有2个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);
}
班级Answer
有一组Collaborator
,但Collaborator
没有一组Answer
。
我需要从Hibernate CriteriaQuery
做的是找到由id给出的答案的协作者。
我已经使用结果转换器使用Hibernate Criteria
(org.hibernate.Criteria
)完成了这项工作,但是在使用CriteriaQuery
时我遇到了困难,因为我没有列表给予加入的答案。
答案 0 :(得分:20)
最后完成了......
以下是代码:
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();
}
答案 1 :(得分:8)
使用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