I have the following table/model:
class Post {
int id;
String comment;
static belongsTo = [category_id:Category];
}
I wish to create a query that can filter out the last Post
(highest id
) per Category
. I want the results in List<Post>
form.
In other words (I believe) in SQL the query would look as follows:
SELECT *
FROM
Post AS source
JOIN (
SELECT MAX(id) AS id, category_id
FROM Post
GROUP BY category_id
) AS filter
ON source.id = filter.id;
If I understand correctly, the first step is to use a HibernateCriteriaBuilder
:
def c = Post.createCriteria();
def results = c.list {
projections {
groupProperty("category_id", "myid")
max("id", "version")
}
}
So my question is a two part:
Am I on the right track?
How can I use the results object to obtain a List<Post>
array?
(Something like: def latest = Post.FindAllByXXX(result);
)
Yes, you are on the right track. I would also add the id property for the Post to my projections:
projections {
property('id')
}
and then collect all Posts using the id to get a list of posts, something like:
def latestPosts = results?.collect{Post.read(it[0])}