Home > Back-end >  How do I select information from ManyToMany Table in JPA?
How do I select information from ManyToMany Table in JPA?

Time:12-19

I have two entities mapped Board and Tag by @ManyToMany to a join table board_tag_table.

How would I return the top 5 most common tag_id in the board_tag_table?

enter image description here

public class Board {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinTable(name = "board_tag_table",
    joinColumns = {
            //primary key of Board
            @JoinColumn(name = "id", referencedColumnName = "id")
    },
    inverseJoinColumns = {
            //primary key of Tag
            @JoinColumn(name = "tag_id", referencedColumnName = "tag_id")
    })
    private Set<Tag> tags = new HashSet<>();

}

public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer tag_id;

    private String tagname;

    @JsonIgnore
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "tags")
    private Set<Board> boards = new HashSet<>();
}



Unable to find how to query within a many to many table

CodePudding user response:

you can pass through foreach and write your query in Tag repository, but I think you can't write query, because they are have list from two sides

CodePudding user response:

Consider using a native query instead.

If you want to use the JPA, you can add a field (Eg. usedCount) in the Tag entity and follow the instructions here https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result.

The query should look like this:

List<Tag> findByUsedCount(Sort sort, Pageable pageable);

  • Related