How do I write a JPA criteria query that matches a collection exactly?

前端 未结 2 1160
挽巷
挽巷 2021-01-14 00:17

I’m using JPA 2.0 with Hibernate 4.1.0.Final. I have a couple of classes, Groups and GroupMembers. Each GroupMember is tied to a user object

@Entity
@Table         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-14 00:43

    You will need different roots for each and every user, as each of them is different from the others (untested):

    final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
    CriteriaQuery criteria = builder.createQuery(Group.class);
    final List predicates = new ArrayList();
    final Root group = criteria.from(Group.class);
    for (final User user : users)
    {
        final Root memberRoot = group.join(Group_.members);
        final Predicate p = builder.equal(memberRoot.get(GroupMember_.user), user);
        predicates.add(p);
    }   // for
    predicates.add(builder.equals(builder.count(group.get(Group_.members)),users.size()))
    criteria.where(builder.and(predicates.toArray(new Predicate[predicates.size()])));
    final TypedQuery results = m_entityManager.createQuery(criteria);
    

提交回复
热议问题