jpa criteria for many to many relationship

天涯浪子 提交于 2019-11-30 04:52:26

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

    }

Using HQL:

You can use this:

Criteria criteria = session.createCriteria(Answer.class);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.createAlias("collaborators", "collaborators");
criteria.add(Restrictions.eq("collaborators.id",desiredCollaboratorId);

to get all the Answers associated to a certain Collaborator.

And this:

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

To get all Collaborators associated to a certain Answer.

Using JPA2 Criteria API you can do something like:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!