【发布时间】:2015-09-17 09:37:27
【问题描述】:
我想保留一个具有许多 1:1 或 1:many 关系的 JPA 实体,只需一次调用 persist。
问题:实体的主键是自动生成的,并在子实体中用作外键。提交事务时,有一个异常指出子实体的外键列上违反了 NotNullConstraint。
内部异常:java.sql.SQLException:ORA-01400:插入 ("SCHEMA"."PROTOCOL_FILE"."PROTOCOL_ID") 中的 NULL 不可能
父实体:
@Entity
@Table(name = "...")
public class Protocol {
@Id
@GeneratedValue(generator="SQ_PROTOCOL", strategy=GenerationType.SEQUENCE)
@SequenceGenerator(name="SQ_PROTOCOL", sequenceName="SQ_PROTOCOL", allocationSize=50)
@Column(name = "PROTOCOL_ID")
private Long protocolId;
@OneToOne(mappedBy="protocol", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private ProtocolFile file;
//Other attributes and getter/setter omitted
}
子实体:
@Entity
@Table(name = "PROTOCOL_FILE")
public class ProtocolFile {
@Id
@Column(name = "PROTOCOL_ID")
private Long protocolId;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinColumns(@JoinColumn(name="PROTOCOL_ID", referencedColumnName="PROTOCOL_ID", updatable=false, insertable=false))
private Protocol protocol;
//Other attributes and getter/setter omitted
}
你知道一个方便的解决方案,这样我就可以在一次调用中持久化所有属于 Protocol 的实体吗?
【问题讨论】:
-
你为什么使用@JoinColumns?你试过没有它吗?
-
@David_Ware 当我删除@JoinColumns 时,插入语句看起来像
INSERT INTO PROTOCOL_FILE(PROTOCOL_ID, ....., PROTOCOL_PROTOCOL_ID) VALUES (?, ...... , ?) bind => [null, ........ , 3351]。如您所见,插入语句使用了正确的 ID,但它正在寻址一个不存在的表列。
标签: java jpa eclipselink