I'm trying to understand how to best implement a polymorphic one-to-many in hibernate.
Eg:
@MappedSuperclass
public class BaseEntity {
Integer id;
// etc...
}
@Entity
public class Author extends BaseEntity {}
@Entity
public class Post extends BaseEntity {}
@Entity
public class Comment extends BaseEntity {}
And now, I'd like to also persist audit information, with the following class:
@Entity
public class AuditEvent {
@ManyToOne // ?
BaseEntity entity;
}
What is the appropriate mapping for auditEvent.entity
? Also, how will Hibernate actually persist this? Would a series of join tables be generated (AuditEvent_Author
, AuditEvent_Post
, AuditEvent_Comment
), or is there a better way?
Note, I'd rather not have my other entity classes expose the other side of the join (eg., List<AuditEvent> events
on BaseEntity
) - but if that's the cleanest way to implement, then it will suffice.
A mapped superclass is not an entity and thus can't be part of an association (as reminded in EJB-199). So either:
BaseEntity
abstract and use a TABLE_PER_CLASS
strategy (see this previous answer)AuditableEntity
entity in the hierarchy and use what would be the most appropriate inheritance strategy for your use case.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With