views:

145

answers:

1

Ruby on Rails has polymorphic relations which are really useful for implementing functionality such as commenting, tagging and rating to name a few. We can have a comment, tag or rating class which has a many to one polymorphic relationship with a commentable, taggable and rateable object. Also, a given domain object can choose to implement any combination of such relations. So, it can for example be commentable, taggable and rateable at the same time.

I couldn't think up of a straightforward way to duplicate this functionality in Hibernate. Ideally, there would be a Comment class which will have a many to one relationship with a Commentable class and a Commentable class will conversely have a one to many relationship with Comments. It will be ideal if the concrete domain classes can inherit from a number of such classes, say Commentable and Taggable. Things seem a little complicated as a Java class can only extend one other class and some code might end up being duplicated across a number of classes.

I wanted to know what are the best practices for modeling such relationships neatly and concisely using Hibernate?

A: 

It seems to me that your question is not hibernate specific but more on the lines of "how can I get around the single inheritance model?"

If implementing interfaces is not what you have in mind AOP (Aspect Oriented Programming) might provide a way for you to do what you wish.

Yaneeve
I was looking for a Hibernate specific answer to my problem, though you are right in that the way to get around the code duplication would be to use AOP. The @DeclareMixin makes it pretty easy to mixin code into Java classes.