Spring Data JPA一对多关系不保存子表

时间:2014-04-24 11:03:19

标签: java sql-server spring hibernate jpa

家长实体

@OneToMany(fetch = FetchType.EAGER, mappedBy = "paramRef", cascade=CascadeType.ALL)
public Set getParamList() { return this.paramList; }

儿童实体

@ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "param_Ref_Id", nullable = false, insertable=false, updatable=false)
public ParamRef1 getParamRef() { return this.paramRef; }

代码要坚持

ParamRef1 pr = new ParamRef1();
pr.setName("TEST PARAM");

Param1 p1 = new Param1() p1.setParamValue("ONE") p1.setParamRef(pr);
Param1 p2 = new Param1() p2.setParamValue("TWO") p2.setParamRef(pr);

Set paramList = new HashSet() paramList.add(p1) paramList.add(p2)

pr.setParamList(paramList)

pr = paramRefDao1.save(pr)

如果步骤正确,请告诉我。我得到以下异常。并且无法理解为什么父ID在子表中不可用

  

引起:org.hibernate.exception.ConstraintViolationException:   无法将值NULL插入列'PARAM_REF_ID',表中   'PARAM';列不允许空值。 INSERT失败。

1 个答案:

答案 0 :(得分:1)

您缺少父表

PARAM_REF_ID的值
ParamRef1 pr = new ParamRef1();
pr.setName("TEST PARAM");
pr.setParamRefId(1); // replace 1 with any other valid id as value