2

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 Answer 1

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) }
        }
    }
1
  • Thanks! You put me on the right track, who would expect an issue with == . The answer is 2-fold, use a >= and put the where in a new block, eg not with an && of another where closure, eg:query = query.where { txnStatus { dateTime >= max(dateTime) } } Though this doesnt actually solve my problem exactly as it only selects the max date from the whole table not for each Txn
    – Steve
    May 16, 2012 at 4:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.