问题
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