我有两个实体通过@ManyToMany将Board和TagMap到连接表board_tag_table。
如何返回board_tag_table中前5个最常见的tag_id?
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<>();
}
找不到如何在多对多表中进行查询
3条答案
按热度按时间0x6upsns1#
你可以通过foreach把你的查询写进标签库,但是我认为你不能写查询,因为它们有来自两个方面的列表
c3frrgcw2#
请考虑改用本机查询。
如果要使用JPA,可以在Tag实体中添加一个字段(例如
usedCount
),然后按照www.example.com中的说明https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result。查询应如下所示:
List<Tag> findByUsedCount(Sort sort, Pageable pageable);
3pvhb19x3#
不要把它看作是试图访问board_tag_table,而是要看一下如何对java实体本身进行访问。这将只是根据它们拥有的电路板数量选择5个顶级标签。“select t.tag_id,count(b)as boardCount from Tag t join t.boards b group by t.tag_id order by boardCount”,然后使用maxResults将返回值限制为5