简体   繁体   中英

JPA query for equality with @ManyToMany relationship

I have these classes:

public class Group {
    @ManyToMany 
    private Set<Person> members;
}
public class Person {
}

I use the following query (based on this question ) to find the groups which contains the specified members list:

select g from Groups g join g.members member where member in :members

(with :members being a Set)

Of course [Person1, Person2] matches [Person1, Person2] and also [Person1, Person2, Person3], ...

Now, I want to find the groups which match exactly the specified members list, ie [Person1, Person2] matches [Person1, Person2] but not [Person1, Person2, Person3].

This should select all groups with the exact members list and no other members.

SELECT group1 FROM Groups group1
    JOIN group1.members member1
WHERE SIZE(:members) = (
        SELECT COUNT(member2) FROM Groups group2
            JOIN group2.members member2
        WHERE group2.id = group1.id)
    AND SIZE(:members) = (
        SELECT COUNT(member2) FROM Groups group2
            JOIN group.members member2
        WHERE group2.id = group1.id AND member2.id IN :members)

Basically, you want all groups with these conditions:

  • The total number of members is equal to the size of the member collection you used as a parameter
  • The total number of parameters in the group matching the ones in the member collection you used as a parameter are also equal to the size of the member collection

This should cover collection content equality. All the ones you are looking for are there and there aren't any more than that.

Also see: Selecting an entity by collection set equality for an alternative, but similar technique.

select g from Groups g inner join g.members member 
    where member.id in :members and not exists(
        select group.id 
            from Groups group inner join group.members xmember 
                where group.id = g.id and xmember.id in :excludeMembers)

members =  [Person1.id, Person2.id]
excludeMembers = [Person3.id]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM