I have a mapped Message object which has a parent-child relationship with itself. So each Message holds a Set<Message> comments. Besides the comments I would like to setup a one-to-one relationship with the last comment made so that I can use the last comment in my Criteria. In SQL I establish this like follows (no comment can have the same postDate so this does not result in double matches for me):
SELECT
parentM.*,
lastComment.*
FROM
messages parentM
left outer join messages lastComment ON
lastComment.parentId=parentM.messageId AND
lastComment.postDate=(SELECT MAX(subM.postDate) FROM messages subM WHERE subM.parentId = parentM.messageId);
Now I would like to know how to set this up in a Hibernate xml mapping but am unsure how to use the formula property or if I should be using a different mechanism. I hoped the following would work but it does not.
<one-to-one name="latestComment"
class="Message"
cascade="none"
property-ref="parent"
formula="postDate=(MAX(allComments.postDate) FROM messages allComments WHERE allComments.parentId=id)"
lazy="proxy">
</one-to-one>
With this mapping I get the result I want as long as there is only one comment. But the forumla is completely ignored. The examples I have seem all use simple formula’s just mapping on a different column, not using a subquery.
Looking forward to some pointers
I could be totally wrong here (please excuse me if I am), but I can’t help feeling that the scenario you are trying to handle may be better served by a triggered procedure on the database. Let the database engine itself handle updating the pointer to the “most recent” comment. That way you don’t have a potentially expensive MAX function – you just look at the postDate for that comment.