我有两个持久类,Comment
和 Vote
。一个 Comment
可以与多个 Vote
相关联,并且它们之间存在 @OneToMany
- @ManyToOne
关系正常工作。我想做的是按最多赞成票对评论进行排序。如果 Vote.up
列为 1
,则 Vote
为赞成票;如果 Vote.up
为 ,则为反对票0
。我正在尝试找出它们的区别
到目前为止,这是我的 HQL,但它不工作
select c from Comment c
order by (
(select count(*) from c.votes v where v.up = 1)
- (select count(*) from c.votes v where v.up = 0)
) desc
有办法吗?
最佳答案
HQL 不支持这种语法,因此您必须为此使用 native 查询:
List<Comment> comments = (List<Comment>) session.createSQLQuery(
"select * " +
"from Comment " +
"where id in ( " +
" select comment_id " +
" from ( " +
" select " +
" c.id as comment_id, " +
" SUM(CASE WHEN v.up=1 THEN 1 ELSE -1 END) AS vote_count " +
" from Comment c " +
" left join Votes v on c.id = v.comment_id " +
" group by comment_id " +
" order by vote_count desc " +
" ) c_v " +
") c_id"
).addEntity(Comment.class).list();
关于java - HQL 按表达式排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30903801/