I'm working in Grails & Groovy but this is a hibernate question. Here's my Grails domain class:
public Card {
// implicit Long id
String name
// ... and over a dozen other fields with various types.
}
I currently have this Hibernate query:
def name = "foo"
def result = session.createQuery("from Card as c where lower(c.name) like ? and c.id in (select max(c2.id) from Card as c2 where c.name = c2.name)")
.setString(0, "%${name}%")
.list()
This gets all Cards with names containing the substring "foo", skipping over any Cards with duplicate names except for the "newest" (I'm assuming that higher ID means 'newer'). I must avoid returning Cards with duplicate names.
In addition to filtering on the name and dodging the duplicate-names problem, I need to filter and/or sort on the other fields in Card. I also need to paginate. I wanted to use the Criteria API to do this, since the approach of generating SQL/HQL leads to maintainability nightmares.
I just can't understand how to do this kind of querying via Criteria API though. There are the detached queries that can be used as a subquery via the Criteria API. However these subqueries all seem to be totally independent of the primary query - I can't get at 'c.name' to compare it to 'c2.name'.
What am I missing here?