简体   繁体   中英

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

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!

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

you can use inheritance exactly. Just annotate the 'CommentableEntity' with @MappedSuperclass annotation which will define this entity as the parent entity. It is always used when you need the parent class to include the "id", "version", "createdAt" and "updatedAt" fields. So I think you have the similar case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM