Hibernate Criteria -- return records where column is distinct

Viewed 17641

Sample database table:

  1. ID = 1, msgFrom = 'Hello', foobar = 'meh'
  2. ID = 2, msgFrom = 'Goodbye', foobar = 'comments'
  3. ID = 3, msgFrom = 'Hello', foobar = 'response'

Sample desired output (generated by hibernate query):

  1. ID = 1, msgFrom = 'Hello', foobar = 'meh'
  2. ID = 2, msgFrom = 'Goodbye', foobar = 'comments'

In the above example, the third record would be excluded from the results since the msgFrom column is the same. Let's say the Java/Hibernate class is called Message. I would like the results to be returned as a list of Message objects (or Objects that can be cast to Message, anyway). I want to use the Criteria API if possible. I saw this example on SO and it seems similar but I cannot implement it correctly as of yet.

 select e from Message e 
    where e.msgFrom IN (select distinct m.msgFrom 
                          from Message m
                          WHERE m.msgTo = ? 
                          AND m.msgCheck = 0");

The reason I am doing this is to have the filtering of distinct records done on the database, so I am not interested in answers where I have to filter anything on the application server.

edit: Article showing basically what I want to do. http://oscarvalles.wordpress.com/2008/01/28/sql-distinct-on-one-column-only/

3 Answers
Related