问题
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