JPA/Hibernate - Polymorphic many-to-one relationship design

Viewed 748

I am attempting to translate an existing Ruby on Rails / Active Record components to a Springboot/JPA/Hibernate stack.

There is an entity model where multiple unrelated types all have the ability to have comments applied to them.

In Rails world this is accomplished by a polymorphic relationship within the model. From a database standpoint, this means I have a comment table with a 'commentable_id' and 'commentable_type' that point back to the entity type and id owning the comment.

I was planning on having an abstract class 'CommentableEntity' which all entities that need to support comments would extend.

I've tried to apply different inheritance strategies but can't find one that fits quite right: - Single table doesn't work because the entities that have comments have disparate attributes that shouldn't be in the same table - Joined table feels awkward because a table just for the CommentableEntity would only have an ID field (is the only shared field amongst those entities)

Is there another approach to achieve this? I'm trying to avoid a model of separate many-to-many tables ex. apple_comments, orange_comments, etc. or separate comment tables like apple_comment (with an apple_id), orange_comment (with an orange_id), etc.

Thanks for any suggestions!

1 Answers
Related