简体   繁体   中英

JPQL query with many to many relationship

Hey so I have a many to many relationship between two tables, Knights and Quests .

I want to write JPQL query where I get quests with id of 1 from knights of id 1 as well, later on I will change it to quest status, but for now I want to make it work:

@Query("select  k.quests from Knight k join k.quests q  where k.id=1 and q.id=1")
Collection<Quest> findDoneStories();

It kinda works, because it gives me quests from knight with id 1, but it gives me all quests rather than only one quest with id 1.

@Entity
@Table(name = "knights")
public class Knight {

    @Id
    @Column(name = "id")
    int id;
    
    @Column
    String name;
    
    @Column(name = "status")
    @Enumerated(EnumType.STRING)
    private KnightEnum status;
    
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "knights_quests", joinColumns = @JoinColumn(name = "id_knights"),
        inverseJoinColumns = @JoinColumn(name = "id_quest"))
    List < Quest > stories;
}
@Entity
@Table(name = "quests")
public class Quest {

    @Id
    @Column(name = "id")
    int id;
    
    @Column
    String name;
    
    @Column(name = "description")
    String description;
    
    @Column(name = "status")
    @Enumerated(EnumType.STRING)
    QuestEnum status;
    
    @Column(name = "story_points")
    int storyPoints;
    
    @ManyToMany(mappedBy = "stories", fetch = FetchType.EAGER)
    List < Sprint > knights;
}

If you want to get only one Quest , your query and method should be like this:

@Query("SELECT DISTINCT q FROM Knight k JOIN k.stories q WHERE k.id = 1 AND q.id = 1")
Quest findDoneStories();

Since it's many to many relation you have to add one more table knights_quests with columns: knighs_id and quests_id where you can store 1 and 1 for example.

Your Entity will be like this:

@ManyToMany() @JoinTable(name = "knights_quests", joinColumns = @JoinColumn(name = "knighs_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "quests_id",referencedColumnName = "name") )

And after you can execute query with simple join, JPQL will handle it under the hood

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