【问题标题】:Inject a sub query into Criteria query将子查询注入 Criteria 查询
【发布时间】:2017-05-15 05:05:26
【问题描述】:

这个方法:

  public List<User> exampleForSO(int size, int page, boolean name, boolean email) {

        Criteria criteria = getSession().getCurrentSession().createCriteria(User.class);

        if (name) {
            criteria.add(Restrictions.isNotEmpty("name"));
        }

        if (email) {
            criteria.add(Restrictions.isNotEmpty("email"));
        }

        criteria.setMaxResults(size);
        criteria.setFirstResult(page);

        List<User> users = criteria.list();

        return users;
    }

产生以下 SQL:

Hibernate: select this_.name as y0_, this_.id as y1_ from users this_ where this_.id is not null limit ? offset ?

我怎样才能实现这个查询?

Hibernate: select this_.name as y0_, this_.id as y1_, COUNT(*) OVER() as overallCount from users this_ where this_.id is not null limit ? offset ?

基本上我想在查询中添加这一行:

COUNT(*) OVER() as overallCount

有什么建议吗?

这可以用 DetachedCriteria 解决吗?

我尝试过的:

  1. 创建一个 DetachedCriteria 并将其作为子查询添加到实际的 Criteria 查询中,这不是一个选项,我不想要子查询。

  2. 生成一个 RawSQL 字符串并尝试将其注入到查询中,但没有成功。

【问题讨论】:

    标签: java postgresql hibernate spring-mvc spring-boot


    【解决方案1】:

    以防万一有人试图达到同样的目的。

    这就是我的做法:

    我在我的用户类中创建了一个字段,如下所示:

    @Formula("COUNT(*) OVER()")
    private Long overallCount;
    

    你可以阅读更多关于Hibernate Formula Annotation here

    【讨论】:

      猜你喜欢
      • 2012-02-15
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 2019-04-01
      • 2012-02-26
      相关资源
      最近更新 更多