简体   繁体   English

JPA 2.0:嵌入式继承的抽象类

[英]JPA 2.0 : Embedded inherited abstract Class

I am using Spring Data JPA with Hibernate and I have the following classes 我正在将Spring Data JPA与Hibernate一起使用,并且有以下课程

@Entity
@Table(name = "ORDER_SLIP")
public class OrderSlip {
    @EmbeddedId
    OrderNumber orderNumber;

    @Embedded
    OrderDetails orderDetails;
}

@Embeddable
public abstract class OrderDetail implements Serializable {

    String commonOrderDetailField;
}    

@Embeddable
public class BuyOrderDetail extends OrderDetail implements Serializable {

    String field1;
    String field2;
}        

@Embeddable
public class SellOrderDetail extends OrderDetail implements Serializable {

    String field3;
    String field4;
}

When I run the program, the fields in the OrderDetail class are embedded in the ORDER_SLIP table. 当我运行程序时,OrderDetail类中的字段嵌入在ORDER_SLIP表中。 The fields of the two subclasses of OrderDetail (BuyOrderDetail and SellOrderDetail) are not as I logically expect them to be. OrderDetail的两个子类(BuyOrderDetail和SellOrderDetail)的字段并不像我逻辑上期望的那样。

Is this possible at all with JPA / Hibernate? JPA / Hibernate完全可以做到吗?

You can implement inheritance between @Embeddable classes. 您可以在@Embeddable类之间实现继承。 You just have to annotate the parent class with @MappedSuperclass too. 您也只需使用@MappedSuperclass注释父类。

So, eg: 因此,例如:

@Embeddable
@MappedSuperclass
public class Parent {
    @Basic
    private String parentProperty;

    // ... getters/setters
}

@Embeddable
public class Child extends Parent {
    @Basic
    private String childProperty;

    // ... getters/setters
}

This way Hibernate (tested with 5.x) will map both parentProperty and childProperty correctly in the Child class. 这样,Hibernate(用5.x测试)将在Child类中正确映射parentPropertychildProperty

In your example you can take advantage of the inheritance only if you use one of your subtypes in the OrderSlip class (not the parent type). 在您的示例中,只有在OrderSlip类中使用子类型之一(而不是父类型)时,您才能利用继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM