【问题标题】:JPA InheritanceType.JOINED how to write relationship entities of parent classJPA InheritanceType.JOINED如何写父类的关系实体
【发布时间】:2019-02-03 18:45:05
【问题描述】:

我有一个父实体类 (Instrument) 和三个子实体(Stock、Bond、Etf)。父类也与类 (InstrumentPrice) 具有 OneToMany 关系。 JPA 连接策略用于父实体和子实体之间。 当一个子项被持久化(例如 Stock)时,Instrument 中的一个条目也会与所有常见属性一起自动持久化。 这很好用。 但是,如何为 InstrumentPrice 类创建一个条目? 在持久化 Stock 后,我是否必须从数据库中读取实体 Instrument,并使用 InstrumentPrice 更新 Instrument?

@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 ...

}

【问题讨论】:

  • 您可以创建一个InstrumentPrice 实例并将InstrumentStock 设置为setInstrument。持久化InstrumetPrice 后,您可以加载InstrumentStock,您将找到您的InstrumentPrice

标签: java hibernate jpa inheritance


【解决方案1】:

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

public void addInstrumentPrice(ip){
   instrumentPriceList.add(ip);
   ip.setInstrument(this);
}

【讨论】:

  • 我必须如何以及何时调用这些方法?当我坚持股票时,我还没有 Instrument 的实例。另外,如何获取 Instrument 的实例?
  • 在坚持之前。 Stock 是 Istrument 的子类,即它继承了此方法。您可以在 Stock 和其他子类上调用它。
  • 它解决了我的问题。我没有意识到 Stock 从 Instrument 扩展而来,因此我可以将 Stock 设置为 InstrumentPrice 上的外键
猜你喜欢
  • 2013-06-01
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多