JPA无法与通用和OneToOne一起使用?

时间:2019-06-09 14:47:37

标签: java jpa

我有2个抽象类A和G,每个抽象类都有2个实现类

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
abstract class A {
    @Id
    protected String id;
}

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
abstract class G<T extends A> {
  @Id
  protected String id;

  @OneToOne(cascade = CascadeType.ALL)
  protected T theA;
}

// ------------------- implemenation classes -------------------

@Entity
@DiscriminatorValue("1")
class A1 extends A {
}

@Entity
@DiscriminatorValue("2")
class A2 extends A {
}

@Entity
@DiscriminatorValue("1")
class G1 extends G<A1> {
}

@Entity
@DiscriminatorValue("2")
class G2 extends G<A2> {
}

// ---------------------- Test codes ----------------------

A2 a2 = new A2();
G2 g2 = new G2();
g2.setTheA(a2);
entityManager.persist(g2);

然后我检查了数据库,表“ G”的“ type”字段是2,这是预期的,但是表“ A”中的“ type”字段是1,所以如果我找到(G2.class,theID)。 getTheA(),将出现ClassCastException:将A1强制转换为A2

是由于类G中的通用性,还是类设计错误?

0 个答案:

没有答案