HQL 按表达式排序

HQL order by expression

我有两个坚持不懈的 类、CommentVote。一个 Comment 可以与许多 Vote 相关联,并且它们之间存在 @OneToMany - @ManyToOne 关系,该关系正常工作。我想做的是按最多赞成票对评论进行排序。如果 Vote.up 列是 1,则 Vote 是赞成票;如果 Vote.up0,则是反对票。我正在尝试找出它们的区别

到目前为止,这是我的 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

有办法吗?

看看这个 sql 例子:

FROM Employee E WHERE E.id > 10 " +
         "ORDER BY E.firstName DESC, E.salary DESC 

是一个hql语句的例子。
你确定你的句子没问题吗?

HQL 不支持这种语法,因此您必须为此使用本机查询:

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