简体   繁体   中英

How to return an object when using GROUP BY in HQL?

I have a table of messages where where I have the columns ID , FROM_ID , TO_ID , DATE , and MESSAGE , with usual entity bean defined. I am trying to write a query where, given a recipient (aka TO_ID ) return the most recent message from each user (ie for each unique FROM_ID , return the record with the greatest DATE ).

The query I came up with is:

SELECT                           
   m.id, m.fromId, m.toId, m.message, max(m.sharedDate),
FROM                             
   Messages m                       
WHERE                            
   m.toId = ?           
GROUP BY                         
   m.fromId    

Now, I can take those columns back and populate a bean with them, but is there a way to have Hibernate do it?

wrap the selected columns in a constructor call:

select new WrapperBean(m.id, m.fromId, m.toId, m.message, max(m.sharedDate))...

where WrapperBean has a constructor with those args.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM