Thursday, May 8, 2014

hibernate count children records

Task and Comment are one to many.
Let's say we have a requirement displaying one task by its id, also displaying the total number of its comments.
Here is the way using criteria and projections to implement it.
A couple of things here...

  • We need add the task properties explicitly, line 6-8, otherwise the query only returns the count result.
  • The alias should be added, otherwise hibernate don't know how to map the result to the domain object. .add(""), "id")
    • (I don't like the above two. It's kind of duplicating the task domain here)
  • criteria.setResultTransformer(Transformers.aliasToBean(Task.class)) tells hibernate to map the result to Task object. But Task does not have the property for commentsCount, we need add a transient property for it.

Good? Bad? like hibernate or hate hibernate? I would say it is not the neat way.
If you have neat way to implement it, let me know!

No comments:

Post a Comment