【发布时间】: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实例并将Instrument或Stock设置为setInstrument。持久化InstrumetPrice后,您可以加载Instrument或Stock,您将找到您的InstrumentPrice
标签: java hibernate jpa inheritance