将 SQL 查询重写为 HQL

rewrite SQL query to HQL

我SQL查询:

SELECT
    tag.id, 
    tag.description, 
    tag.`name`, 
    COUNT(question_has_tag.question_id)
FROM
    question_has_tag
INNER JOIN
    question
ON 
    question.id = question_has_tag.question_id
INNER JOIN
    tag
ON 
    question_has_tag.tag_id = tag.id
GROUP BY
    tag.id

一切正常。 但我需要将它重写为 HQL,有人知道吗? 我试过这个,但它不起作用:

list = entityManager.createQuery("SELECT " +
            "t.id, " +
            "t.description, " +
            "t.name, " +
            "COUNT(q.id) " +
            "FROM Tag t INNER JOIN Question q ON t.id = q.id " +
            "GROUP BY t.id").getResultList();

抱歉,不是所有信息,我有 3 个 table 标签、问题和 question_has_tag(由休眠自动创建)标签和问题具有多对多关系

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

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

试试这个

list = entityManager.createQuery("SELECT " +
            "t.id, " +
            "t.description, " +
            "t.name, " +
            "COUNT(q.id) " +
            "FROM Tag t JOIN t.questions q" +
            "GROUP BY t.id").getResultList();