问题描述
例如:
$ b
$ b我想了解如何最好地实现hibernate中的多态一对多。 $ b
@MappedSuperclass
公共类BaseEntity {
整数id;
//等等...
}
@Entity
public class作者extends BaseEntity {}
@Entity
公共类Post扩展BaseEntity {}
@Entity
public class Comment BaseEntity {}
现在,我还想坚持审计信息,与以下类:
@实体
public class AuditEvent {
@ManyToOne //?
BaseEntity实体;
$ / code>
auditEvent.entity
?另外,Hibernate会如何坚持下去?会生成一系列连接表( AuditEvent_Author
, AuditEvent_Post
, AuditEvent_Comment
注意,我宁愿没有其他实体类暴露连接的另一端(例如, 在
- 但如果这是最简洁的实现方式,那就足够了。 / p> BaseEntity
)上列出< AuditEvent>事件
映射超类不是实体,因此不能成为关联的一部分(如)。所以:
- 使您的
BaseEntity
摘要并使用TABLE_PER_CLASS
策略(请参阅此) - 在层次结构中引入另一个
AuditableEntity
实体,并使用最为您的用例提供适当的继承策略。 - 考虑使用
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:
- make your
BaseEntity
abstract and use aTABLE_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
这篇关于Hibernate - 持久化多态连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!