我对JPA中的继承进行了研究,并resources我发现每个实体只使用一个父类(super class)。但没有使用 2 个或更多父类(super class)的示例。
这个怎么样:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = “Abstract_One”)
public abstract class AbstractOne {
@Id
protected Long id;
…
}
@Entity(name = “A”)
@DiscriminatorValue(“A”)
public class A extends AbstractOne {
@Column
private int a;
…
}
@Entity(name = “B”)
@DiscriminatorValue(“B”)
public class B extends A {
@Column
private int b;
…
}
可以这样做吗?
如果可能,哪种继承策略允许这样做并提供最佳的数据一致性?
最佳答案
我只能想象下面的例子
@MappedSuperclass
public class A
{
...
@Id
@Column(name = "RECID")
public Long getId()
...
}
@MappedSuperclass
public class B extends A
{
...
@Column(name = "COL1")
public String getColumn1()
...
}
@Entity(name="INH_TAB1")
public class C extends B
{
...
@Column(name = "COL2")
public String getColumn2()
...
}
另外,在 Bauer、King、Gregory 所著的优秀著作《Java Persistence with Hibernate》中,我发现以下内容对于解决此问题可能有用:
6.5 Mixing inheritance strategies
You can map an entire inheritance hierarchy with the TABLE_PER_CLASS, SINGLE_TABLE, or JOINED strategy. You can’t mix them — for example, to switch from a table-per-class hierarchy with a discriminator to a normalized table-per-subclass strategy. Once you’ve made a decision for an inheritance strategy, you have to stick with it. This isn’t completely true, however. By using some tricks, you can switch the mapping strategy for a particular subclass. For example, you can map a class hierarchy to a single table, but, for a particular subclass, switch to a separate table with a foreign key–mapping strategy, just as with table-per-subclass.
但是,我无法想象任何实际情况,这种复杂的继承层次结构是必需的/有用的,而且它还会影响性能。
关于java - JPA继承两个或多个父类(super class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58565496/