jpa criteria for many to many relationship

前端 未结 2 587
不思量自难忘°
不思量自难忘° 2020-12-14 09:21

I have 2 POJO classes in Java, Answer and Collaborator, in a many-to-many relationship.

class Answer {
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTa         


        
相关标签:
2条回答
  • 2020-12-14 09:27

    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
    
    0 讨论(0)
  • 2020-12-14 09:38

    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();
    
        }
    
    0 讨论(0)
提交回复
热议问题