【问题标题】:Grails "max" subquery with an association, to get only the latest of a hasMany带有关联的 Grails“max”子查询,仅获取最新的 hasMany
【发布时间】:2012-05-16 10:08:49
【问题描述】:

简化的领域模型: “Txn”(如在事务中)有许多“TxnStatus”。 TxnStatus 有一个 dateTime

这是一个遗留映射,所以我无法更改数据库,即 Txn 上的映射:

  static mapping = { 
    txnStatus column: 'MessageID', ignoreNotFound: true, fetch: 'join'
  }

我需要根据一些动态构建的条件来获取 Txns,目前使用 GORM 的 'where' 查询,效果很好;但我还需要获得 latest txnStatus。

试过了:

def query = Txn.where {
   txnStatus { dateTime == max(dateTime) }    
}

给:java.lang.ClassCastException: org.hibernate.criterion.DetachedCriteria cannot be cast to java.util.Date

也试过了:

 def query = Txn.where {
       txnStatus.dateTime == max(txnStatus.dateTime)    
    }

给出:

Compilation Error: ... 
            Cannot use aggregate function max on expressions "txnStatus.dateTime"

在这个阶段,我正在考虑改用 HQL...任何帮助表示感谢!

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    几天前有一个问题与此非常相似。似乎使用带有“max”子查询的 where 查询不适用于 ==

    OP 能够让它与

    这是一个非常疯狂的猜测 -

        Txn.where {
            txnStatus  {
              dateTime == property(dateTime).of { max(dateTime) }
            }
        }
    

    【讨论】:

    • 谢谢!你让我走上了正确的轨道,谁会期望 == 有问题。答案是 2 倍,使用 >= 并将 where 放在一个新块中,例如,不要使用 && 另一个 where 闭包,例如:query = query.where { txnStatus { dateTime >= max(dateTime) } } 虽然这实际上并没有完全解决我的问题,因为它只从整个表中选择最大日期,而不是每个 Txn
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    相关资源
    最近更新 更多