rewrite SQL query to HQL

被刻印的时光 ゝ 提交于 2021-01-29 20:19:32

问题


I've SQL query:

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

All works good. But I need to rewrite it to HQL, some one have any idea? I tried this, but it doesn't work:

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();

Sorry it not all information, I've 3 table tag, question and question_has_tag (auto created by hibernate) tag and question has ManyToMany relations

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

and

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

回答1:


Try this

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();


来源:https://stackoverflow.com/questions/61940131/rewrite-sql-query-to-hql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!