Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate - Persisting polymorphic joins

Tags:

java

hibernate

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.

like image 653
Marty Pitt Avatar asked May 28 '10 12:05

Marty Pitt


1 Answers

A mapped superclass is not an entity and thus can't be part of an association (as reminded in EJB-199). So either:

  • make your BaseEntity abstract and use a TABLE_PER_CLASS strategy (see this previous answer)
  • introduce another AuditableEntity entity in the hierarchy and use what would be the most appropriate inheritance strategy for your use case.
  • consider using Envers
like image 116
Pascal Thivent Avatar answered Sep 29 '22 21:09

Pascal Thivent