您好,我是 JPA 新手,我无法理解它如何处理继承。
我有一个需要在不更改数据库方案的情况下解决的特定问题,但如果您找不到解决方案,我将不胜感激使用不同数据库方案的解决方案建议(欢迎 Hibernate/TopLink 解决方案)。
如果我不清楚或者您需要更多信息,请告诉我。提前致谢!
我有这个数据库:
TABLE Fruit
Id Varchar (10) Primary Key
size Varchar (10)
fruit_type Varchar(10)
TABLE Apple
Id Varchar (10) Primary Key Foreign Key references Fruit.Id
Apple_Property Varchar(10)
到目前为止,我的实体如下所示:
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="fruit_type", discriminatorType=DiscriminatorType.Char)
@DiscriminatorValue(value="fruit")
public class Fruit implements Serializable {
@Id
protected String Id;
protected String size;
}
@Entity
@DiscriminatorValue(value="apple")
//@PrimaryKeyJoinColumn(name="Id" , referencedColumnName="Id")
public class Apple extends Fruit implements Serializable {
private String Apple_Property;
}
目前我可以毫无问题地保留 Fruit 对象。
仅当 Apple 对象的 Fruit 对象尚未持久化时,Apple 对象才会持久化。
如果我尝试用已经持久化的 Fruit 对象来持久化一个 apple 对象:
Fruit fruit1 = new Fruit("1", "Small");
Apple apple1 = new Apple(fruit1, "red");
provider.create(fruit1);
provider.create(apple1);
我会收到错误,因为 JPA 尝试在 Fruit 表上创建 Id=“1”的新行
这已经存在了。
..