有人能帮忙把这个mysql查询翻译成jpql或hql吗?

6yt4nkrj  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(259)

别忘了检查下面的图片
物体:
1) 问题
2) 标签
这种关系有很多种

public class Question {

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

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "question_has_tag",
        joinColumns = @JoinColumn(name = "question_id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id"))
private List<Tag> tags;

public class Tag {

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

@NotNull
@Column
private String name;
@ManyToMany(mappedBy = "tags", fetch = FetchType.LAZY)
@ContainedIn
private List<Question> questions;

mysql查询如下:

select t.id, t.name, count(question_has_tag.tag_id) as i from tag as t join question_has_tag 
on id = question_has_tag.tag_id group by id order by i desc;

需要翻译成jpql或hql
主要目标是获得最频繁的标签列表like:enter image 此处为说明

nkkqxpd9

nkkqxpd91#

尝试:

Query q = entityManager.createQuery("select t.id, t.name, count(t.id) from Tag t join t.questions group by t.id,t.name");
List<Object[]> res = q.getResultList();
for(Object[] row:res) {
    System.out.println(row[0]+" "+row[1]+" "+row[2]);
}

给定的jpa查询(通过hibernate)转换为sql:

select tag0_.id as col_0_0_, tag0_.name as col_1_0_, count(tag0_.id) as col_2_0_ from Tag tag0_ inner join question_has_tag questions1_ on tag0_.id=questions1_.tag_id inner join Question question2_ on questions1_.question_id=question2_.id group by tag0_.id , tag0_.name

相关问题