jpa多对多关系的标准 [英] jpa criteria for many to many relationship
问题描述
class答案在Java,Answer和Collaborator中我有2个POJO类,在多对多的关系中。 {
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name =ANSWERS_COLLABORATORS,joinColumns = {@JoinColumn(name =aid)},inverseJoinColumns = {@JoinColumn(name = cid)})
private Set< Collaborator>协作者=新的HashSet<协作者>(0);
Class Answer
has一组协作者
,但。
我需要从Hibernate做些什么 CriteriaQuery
是为id找到的答案寻找协作者。
我已经用Hibernate Criteria
( org.hibernate.Criteria
)使用结果转换器完成了这项工作,但是I' m在使用 CriteriaQuery
时陷入困境,因为我没有给出连接的答案列表。
完成后,终于...
以下是代码:
public List< Collaborator> getCollaborators(Long answerId){
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<协作者> criteriaQuery = criteriaBuilder
.createQuery(Collaborator.class);
Root< Answer> answerRoot = criteriaQuery.from(Answer.class);
criteriaQuery.where(criteriaBuilder.equal(answerRoot.get(Answer_.id),
answerId));
SetJoin<答案,协作者> answers = answerRoot
.join(Answer_.collaborators);
CriteriaQuery<协作者> cq = criteriaQuery.select(answers);
TypedQuery<协作者> query = entityManager.createQuery(cq);
返回query.getResultList();
}
I have 2 POJO classes in Java, Answer and Collaborator, in a many-to-many relationship.
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);
}
Class Answer
has a set of Collaborator
, but a Collaborator
doesn't keep a set of Answer
.
What I need to do from Hibernate CriteriaQuery
is to find the collaborators for an answer given by id.
I have already done this with Hibernate Criteria
(org.hibernate.Criteria
) using result transformer, but I'm stuck when it comes to using CriteriaQuery
, because I don't have a list of answers to give to the join.
It's done, finally...
Here's the code:
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();
}
这篇关于jpa多对多关系的标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!