hibernate - 查询中的动态排序

时间:2017-06-22 21:40:38

标签: spring hibernate

我有一个Dao方法返回"帖子"看起来像这样:

public List<PostDTO> getPosts() {
    Session session = sessionFactory.getCurrentSession();

    return postList = session
            .createQuery("select new com.poster.app.dto.PostDTO(p.id, p.date, p.title, p.text, p.imageUrl, p.author, p.category, count(c.post.id)) "
                            + "from Post as p left join Comment as c ON p.id = c.post.id group by p.id",
                    PostDTO.class).getResultList();
}

所以它基本上只是创建查询并在这种情况下返回dto。问题是,我需要使用不同的排序来获取完全相同的列表BUT。就像我需要通过&#34;最新&#34;,&#34;最受欢迎&#34;并通过&#34;评论编号&#34;我希望用一种方法做到这一点,而不是为每种方法创建3种方法(&#34;最新&#34;,&#34;最受欢迎&#34;以及&#34;注释号&#34;),怎么能我在休眠中做到了吗?

1 个答案:

答案 0 :(得分:0)

您可以选择:

  • 使用api条件构建查询并动态添加您的order by子句。
  • 根据您的参数
  • 在查询末尾添加order by子句

ex with 2nd option:

 public List<PostDTO> getPostsOrderBy(String orderParam) 
 {
    Session session = sessionFactory.getCurrentSession();

    String query = "select new com.poster.app.dto.PostDTO(p.id, p.date, p.title, p.text, p.imageUrl, p.author, p.category, count(c.post.id)) "
            + "from Post as p left join Comment as c ON p.id = c.post.id group by p.id order by "+ orderParam;


    return postList = session.createQuery(query,PostDTO.class).getResultList();
}