Grails “max” subquery with an association, to get only the latest of a hasMany

拥有回忆 提交于 2019-12-07 22:58:26

问题


The simplified domain model: 'Txn' (as in Transaction) hasMany 'TxnStatus'. TxnStatus has a dateTime

This is a legacy mapping so I cant change the DB, the mapping on Txn:

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

I need to get Txns based on a number of dynamically built criteria, currently using GORM's 'where' query, it works well; BUT I need to also get only the latest txnStatus.

Tried:

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

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

also tried:

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

which gives:

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

At this stage I am thinking of changing to HQL...any help appreciated!


回答1:


There was a question a couple of days ago very similar to this. It appears that using where queries with a 'max' subquery doesn't work well with ==

The OP was able to get it to work with < and worked around it that way. Looking at the docs on where queries has not helped me figure this one out.

Here is a really wild guess -

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


来源:https://stackoverflow.com/questions/10610338/grails-max-subquery-with-an-association-to-get-only-the-latest-of-a-hasmany

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!