【发布时间】:2012-05-16 05:32:01
【问题描述】:
这是我找不到解决方案的问题,我想这要么是不可能的,要么是我的整个想法都朝着错误的方向发展。
最初我的 JPA 层次结构的一部分是这样的:
@MappedSuperclass
public abstract class AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
.....
}
@Audited
@Entity
@Table(name = "T_MEETING")
public class Meeting extends AbstractEntity implements Groupable {...}
@Audited
@Entity
@Table(name = "T_QUESTION")
public class Question extends AbstractEntity implements Groupable {...}
这个数据库已经使用了一段时间,直到需要在某些对象中自定义字段。
我决定遵循以下路线 - 将抽象实体作为具有自定义字段的对象的基础:
@Audited
@Entity
@Table(name = "T_CF_OBJECT")
@Inheritance(strategy = InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name = "ID", referencedColumnName = "CF_OBJECT_ID")
public abstract class EntityWithCustomFields extends AbstractEntity {...}
@Audited
@Entity
@Table(name = "T_QUESTION")
public class Question extends EntityWithCustomFields implements Groupable {...}
@Audited
@Entity
@Table(name = "T_MEETING")
public class Meeting extends EntityWithCustomFields implements Groupable {...}
我尝试了不同的选项,但总是有问题:
-
我猜,JPA 提供程序(在我的情况下是休眠的)首先插入父级,因此它的
CF_OBJECT_ID是nullHibernate:插入 t_cf_object (id, cf_object_id) 值 (null, ?) Hibernate:插入 t_meeting (active, date, c_group, last_notification_date, only_for_members, place, questions_order, subject, update_date, id) 值 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1234563 ID。一开始这很好,但是我们已经在两个表中都有大量记录,并且它们在
id 列中具有相同的值。不能更改表格中的ids。
在我的情况下使用继承的正确方法是什么,以便尽可能无缝地进入?很高兴了解如何首先使休眠持久子类实例,然后将其 id 传递给持久的超类。必须有注释,对吧?
编辑:至于建议使用@MappedSuperclass
由于以下原因,我真的不能使用@MappedSuperClass。父类EntityWithCustomFields 用于通过CustomFieldValue 类的ManyToOne 关系引用。代码如下:
@Entity
@Audited
@Table(name = "T_CF_VALUES")
public class CustomFieldValue extends AbstractEntity {
@ManyToOne
@JoinColumn(name = "customFieldObject", nullable = false)
private EntityWithCustomFields customFieldObject;
....
}
@Audited
@Entity
@Table(name = "T_CF_OBJECT")
@Inheritance(strategy = InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name = "ID", referencedColumnName = "CF_OBJECT_ID")
public abstract class EntityWithCustomFields extends AbstractEntity {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "customFieldObject", cascade = CascadeType.ALL)
private List<CustomFieldValue> customFields;
....
}
我认为@MappedSuperclass 不能用于这类事情。
【问题讨论】:
标签: hibernate inheritance jpa