简体   繁体   中英

JPA : handling many to many relationships

I am using jpa-api 2.0-cr-1.(Maven)

I have 2 classes Person and Tag.

Each person can have multiple tags and vice-versa.

Now I want to retrieve all persons belonging to all given tags.
For eg
person1 is tagged with "tall","fat" and "bold"
person2 is tagged with "tall" and "thin"
person3 is tagged with "tall" and "bold"

Now the problem is that if I query for ["tall","bold"]
I should get [person1,person3]
ie I want to retrieve persons who belong to all of the given tags.

public class Person {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "person_name")
    private String personName;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "person_tag", joinColumns = { @JoinColumn(name = "person_id") }, inverseJoinColumns = @JoinColumn(name = "tag_id"))
    private Set<Tag> tags;
}

public class Tag {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "person_tag", joinColumns = { @JoinColumn(name = "tag_id") }, inverseJoinColumns = @JoinColumn(name = "person_id"))
    private Set<Person> persons;

if you are looking for a query, you could try the following one. here I used the "tag.name", not id. but you know how to change it if it works for you.

select p from Person p 
  left join p.tags as t where t.name in ("tall","bold") 
group by p having count(p)=2

btw, I didn't test it. hope it helps.

Select p from Person p join p.tags t1 join p.tags t2 where t1.name = 'tall' and t2.name = 'bold'

参见http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#JOIN

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