【发布时间】:2020-04-19 11:10:57
【问题描述】:
我正在使用@OneToMany 注释来保存父实体和子实体,但在特定情况下保存子实体时遇到问题。
子实体在两种情况下被保存:
- 在第一次插入有孩子的父母时。
- 当数据库中没有插入/保存子项时,在更新父项和子项期间 在第一次插入中
但是当父级与子级 1 一起插入,然后在父级更新期间我尝试插入子级 2 时,我无法保存子级 2
它失败了,但有以下异常:
o.h.e.jdbc.spi.SqlExceptionHelper - ORA-01407: cannot update ("app_Name"."Child_entity"."REFERENCE_ID") to NULL\n
23:22:06.068 ERROR o.h.i.ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
请看我的代码如下:
@Data
@Entity
@Table("Parent_table")
public class Parent_entity implements Serializable {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval =true)
@JoinColumn(name="REFERENCE_ID")
private Set<Child_Entity> childrens ;
}
@Data
@Entity
@Table("child_table")
public class Child_entity implements Serializable {
@Id
@GeneratedValue(generator = "seq_gen", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "seq_gen", sequenceName = "child_SEQ",allocationSize=1)
@Column(name ="col_name")
private Integer asSeq;
@Column(name ="REFERENCE_ID")
private String referenceid;
}
在映射器类中,我明确设置了父表的主键。
Oracle 数据库端我添加了以下外键约束
ALTER TABLE child_table
ADD CONSTRAINT FK_parent_table
FOREIGN KEY (REFERENCE_ID)
REFERENCES Parent_table(REFERENCE_ID);
我浏览过关于 stackoverflow 的类似问题,这表明如果您使用现有列作为外键,则该列的现有值不应为空。 但在我的情况下,列“REFERENCE_ID”已经不可为空。
如果我需要添加其他内容以使其正常工作,请告诉我或建议。
谢谢。
编辑: 在更新场景中,Hibernate 正在生成以下查询:
update child_table set reference_id=null where reference_id=? and child_seq=?
其中reference_id是Parent的主键,child_seq是Child的主键
知道为什么 hibernate 会尝试更新 Parent 的主键 我在子实体中明确设置父主键的值
【问题讨论】:
标签: spring-data-jpa parent-child one-to-many