JPA InheritanceType.JOINED如何编写父类的关系实体

时间:2019-02-03 18:45:06

标签: java hibernate jpa inheritance

我有一个父级实体类( Instrument ),其中有三个子级( Stock,Bond,Etf )。父类与类( InstrumentPrice )也具有OneToMany关系。在父实体和子实体之间使用JPA加入策略。 当一个孩子被保留(例如股票)时,Instrument中的条目也会自动保留所有常见属性。 很好 但是,如何为 InstrumentPrice 类创建一个条目? 持有存货后,我是否必须从数据库读取实体工具,并用InstrumentPrice更新工具?

@MappedSuperclass
public abstract class BaseEntity implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected int id;

}

父类仪器

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "instr_type", discriminatorType = DiscriminatorType.STRING, length = 1)
@Table(name = "instrument")

public class Instrument extends BaseEntity {

    @Column
    private String symbol;

    @Column
    private String isin;

    @Column
    private String name;

    @Column
    private boolean active;

    @OneToMany(mappedBy = "instrument", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<InstrumentPrice> instrumentPriceList;

    // public getters & setters
    ....

InstrumentPrice

@Entity
@Table(name = "instrumentprice")
public class InstrumentPrice extends BaseEntity {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "instrument_id", nullable = false)
    private Instrument instrument;

    @Column
    private LocalDate date;
    @Column
    private double open;
    @Column
    private double high;
    @Column
    private double low;
    @Column
    private double close;
    @Column
    private long volume;

    // public getters & setters
    ....

儿童班股票

@Entity
@DiscriminatorValue("S")
@PrimaryKeyJoinColumn(name = "id")
@Table(name = "stock")
public class Stock extends Instrument { 

...  fields specific to Stock ...

}

1 个答案:

答案 0 :(得分:0)

您必须设置双方关系。在Instrument类中,创建用于添加InstrumentPrice实体的方法。

a