java - HQL 按表达式排序

标签 java sql database hibernate hql

我有两个持久类,CommentVote。一个 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/

相关文章:

java - 没有必要将 super() 放在构造函数中吗?

sql - 在所有查询中都有 TRANSACTION

mysql - Laravel Eloquent 支持 MariaDb 动态列

sql-server - 在 SQL Server 中分页时保留总结果信息

mysql - 将数据从一个表复制到另一个表。数据库不同表结构不同

java - 带有 Eclipse 插件的 Java Web 应用程序框架

java - 当 Java 应用程序位于包中时,如何从命令行运行它?

php - 将数据从一个数据库插入另一台服务器上的另一个数据库 - 服务器未链接

java - 如何通过从 jsp 的下拉列表中选择值来调用 Spring MVC Portlet Controller 方法

mysql - SQL 唯一键语法