JPA和继承
时间:2020-03-06 15:05:18 来源:igfitidea点击:
我有一些JPA实体,它们彼此继承,并使用鉴别器确定要创建的类(到目前为止尚未试用)。
@Entity(name="switches") @DiscriminatorColumn(name="type") @DiscriminatorValue(value="500") public class DmsSwitch extends Switch implements Serializable {} @MappedSuperclass public abstract class Switch implements ISwitch {} @Entity(name="switch_accounts") public class SwitchAccounts implements Serializable { @ManyToOne() @JoinColumn(name="switch_id") DmsSwitch _switch; }
因此,在SwitchAccounts类中,我想使用基类Switch,因为在运行时之前我不知道将创建哪个对象。我怎样才能做到这一点?
解决方案
我认为我们无法使用当前的对象模型。 Switch类不是实体,因此不能在关系中使用。 @MappedSuperclass注释是为了方便起见,而不是为了编写多态实体。没有与Switch类关联的数据库表。
我们或者必须使Switch成为一个实体,或者以其他方式进行更改,以使我们拥有一个作为实体的公共超类。
由于切换类不是实体,因此不能在实体关系中使用...不幸的是,我们必须将mappingsuperclass转换为实体,以使其包含在关系中。
作为前面的评论者,我同意类模型应该有所不同。我认为以下内容就足够了:
@Entity(name="switches") @DiscriminatorColumn(name="type") @DiscriminatorValue(value="400") public class Switch implements ISwitch { // Implementation details } @Entity(name="switches") @DiscriminatorValue(value="500") public class DmsSwitch extends Switch implements Serializable { // implementation } @Entity(name="switches") @DiscriminatorValue(value="600") public class SomeOtherSwitch extends Switch implements Serializable { // implementation }
我们可以通过使构造函数受保护来直接阻止Switch的实例化。我相信Hibernate接受这一点。