【问题标题】:Can't get "count" and "groupBy" with Grails DetachedCriteria无法使用 Grails DetachedCriteria 获得“count”和“groupBy”
【发布时间】:2014-06-21 02:10:30
【问题描述】:

我有一个用于查询的域类。

TourIndex{
     Long tourId
     String country
     String location
     int availability
     // ... more fields
}

我们使用一系列“动态”标准构建器基于一系列配置进行搜索,这些配置基本上会导致执行:

def detachedCriteria = new DetachedCriteria(TourSearchIndex)

detachedCriteria = detachedCriteria.build { eq('country','AR') }
detachedCriteria = detachedCriteria.build { eq('location','salta') }

我想重新利用这个逻辑并在表单中获取可用的过滤器及其各自的结果

[['location1', '3'], ['location2', '5']]

我最疯狂的猜测是:

detachedCriteria = detachedCriteria.build{
  projections{
    property('location')
    countDistinct('tourId')
  }
}

但这会导致一个非常明显的错误

Caused by: org.h2.jdbc.JdbcSQLException: Column "THIS_.LOCATION" must be in the GROUP BY list; SQL statement:
select this_.location as y0_, count(distinct this_.tour_id) as y1_ from tour_search_index this_ where this_.country=? [90016-173]

根据How to Group property in Order Clause using Grails Criteria,使用 createCriteria 我有一种方法可以使计数不同

def criteria = TourSearchIndex.createCriteria()

def result = criteria.list {
  projections{
    groupProperty('location')
    countDistinct('id','idDistinct')
  }
  order('idDistinct','desc') 
}

但我想使用已使用应用程序其余部分的 DetachedCriteria,是否有解决方法?我认为缺少的是 DetachedCriteria 内部类的 DetachedProjection 中的“groupProperty”。

提前致谢。

【问题讨论】:

    标签: hibernate grails detachedcriteria


    【解决方案1】:

    我不确定,但是从看到您的条件和 detachedCriteria 查询以及错误来看,您可以试试这个

    detachedCriteria = detachedCriteria.build{
      projections{
        groupProperty('location')
        countDistinct('tourId')
      }
    }
    

    【讨论】:

    • 感谢 Suganthan,但这会引发 MissingMethodException。 groovy.lang.MissingMethodException:没有方法签名:grails.gorm.DetachedCriteria.groupProperty() 适用于参数类型:(java.lang.String) 值:[location] 可能的解决方案:getProperty(java.lang.String), geProperty(java.lang.String, java.lang.String), gtProperty(java.lang.String, java.lang.String), property(java.lang.String), hasProperty(java.lang.String) 我可以参见 DetachedCriteria 的内部类 DetachedProjections。我想如果没有人可以帮助我,我可以在 grails 项目中提出一个 jira。
    【解决方案2】:

    对于 DetachedCriteria,语法有点不同。

    detachedCriteria = detachedCriteria.build{
    
    }.projections{
        property('location')
        countDistinct('tourId')
    }.list()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 2022-10-12
      • 1970-01-01
      相关资源
      最近更新 更多