object references an unsaved transient instance - save the transient instance异常想

    最近在维护一个业务系统,当系统发生级联更新的时候,出现了这样的一个问题。

    object references an unsaved transient instance - save the transient instance before flushing: project.womensleague.components.domain.entity.VolunteerTrainingRecord

     在一对多关系时当我要在子表里新增一条纪录的时候,就出现这个异常。然后在网上查了很多资料,有很多说把cascade 设为“save-update”,然后把cascade 设为 “all”。然后就正常了。

      这是为什么呢。我们知道这个问题出现原因是“主表没有保存完,子表就保存了”,也就是说当主表还在瞬时态的时候,子表是不能保存的。这时若果新增一条记录,保存顺序就会错。

      原来我在方法里使用了merge,当你使用merge的时候

      当 cascade

      设置为all时:所有情况都进行级联。这是一个全面的解决办法

      设置为save-update时,只有主表进行更新或添加时才进行级联。这个方法。

      也就是当使用merge(级联更新)时,save-update是属无法触发级联操作,无法维护实体的关系。这时最好的解决方法是把 cascade="save-update,merge" ,因为all使所有操作都拥有级联属性。这使我们其他不必要级联的操作都变成级联操作,这样很危险。会使执行一些系统业务需求以外的操作。

最后的理想设置是

       

扫描二维码关注公众号,回复: 469759 查看本文章
<bag cascade="save-update,merge" name="serviceRecords"  order-by="startdate desc" >
			<key column="volunteerid"  not-null="true"/>
			<one-to-many class="VolunteerServiceRecord"  />
		</bag>
		
		<bag cascade="save-update,merge" name="trainingRecords" order-by="startdate desc">
			<key column="volunteerid" not-null="true" />
			<one-to-many class="VolunteerTrainingRecord" />
		</bag>
 

猜你喜欢

转载自only-life.iteye.com/blog/2253801