休眠不插入父

时间:2012-08-28 13:03:05

标签: java hibernate hibernate-mapping

我有两个带有hibernate的映射类:

SETTLEMENT_MODEL_GROUP (父母):

@Entity
@Table(name = "MODEL_GROUP")
public class SettlementModelGroup
{

//omitted some not fields

@OneToMany( fetch = FetchType.LAZY, mappedBy = "modelGroup" )
private List<SettlementModel> settlementModels;

}

SETTLEMENT_MODEL 孩子:

@Entity
@Table(name = "MODEL")
public class SettlementModel
{

//omitted some not fields

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "MODEL_GROUP_ID", insertable = false, updatable = false, nullable = false)
private SettlementModelGroup modelGroup;

}

现在我正在简单地插入数据库:

  SettlementModel model = new SettlementModel();
  SettlementModelGroup settlementModelGroup = modelManager.getModelGroup( modelGroupId );

  //setting other fields for model
  model.setModelGroup( settlementModelGroup );

  sessionFactory.getCurrentSession().save( model );

给我:

SQL Error: 1400, SQLState: 23000
ORA-01400: cannot insetr NULL into ("MYSCHEMA"."MODEL"."MODEL_GROUP_ID")

为什么hibernate不插入父ID,虽然它存在并被创建?即使在标准输出上给它也会返回正确的ID ......

此外,我无法从 SettlementModel 中删除insertable = false, updatable = false,因为它在部署期间给出了Hibernate错误

2 个答案:

答案 0 :(得分:2)

添加到@OneToMany cascade = CascadeType.ALL
从父

中删除nullable = false

答案 1 :(得分:1)

尝试将cascade = CascadeType.ALL用于hbm文件,您在其中定义了oneToMany关系