许多关系的jpa标准

时间:2011-11-15 11:24:35

标签: java hibernate many-to-many jpa-2.0 criteria

我在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 Criteriaorg.hibernate.Criteria)完成了这项工作,但是在使用CriteriaQuery时我遇到了困难,因为我没有列表给予加入的答案。

2 个答案:

答案 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