2011-11-15 173 views
12

我在Java,Answer和Collaborator中有2個POJO類,在多對多的關係中。jpa多對多關係的標準

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。 我需要從休眠CriteriaQuery做什麼是找到合作者爲id給出的答案。

我曾與Hibernate Criteriaorg.hibernate.Criteria)使用效果的變壓器已經做到了這一點,但我堅持,當談到使用CriteriaQuery,因爲我沒有答案的名單給到加盟。

回答

14

它的完成,終於...

下面的代碼:

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

    } 
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標準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