日期:2014-05-17  浏览次数:20827 次

Hibernate级联保存,父表为空,先存子表,保存提示外键为null的错误怎么解决?
本帖最后由 dragon08 于 2013-01-17 12:55:04 编辑
两张表:父表people,子表picture
people的映射文件如下,省略字段的描述

<hibernate-mapping package="com.myproject.entity">
<class name="People" table="PEOPLE">
<meta attribute="sync-DAO">false</meta>
<cache usage="read-write"/>
<id name="id" type="java.lang.Long" column="PEOPLE_ID">
<generator class="sequence">
<param name="sequence">S_PEOPLE</param>
</generator>
</id>
<set name="pictures" inverse="true">
<key column="PEOPLE_ID"></key>
<one-to-many class="Picture"/>
</set>
</class>
</hibernate-mapping>


picture的映射文件如下,省略字段的描述

<hibernate-mapping package="com.myproject.entity">
<class name="Picture" table="PICTURE">
<meta attribute="sync-DAO">false</meta>
<cache usage="read-write"/>
<id name="id" type="java.lang.Long" column="PICTURE_ID">
<generator class="sequence">
<param name="sequence">S_PICTURE</param>
</generator>
</id>
<many-to-one name="people" column="PEOPLE_ID" class="People" not-null="false"></many-to-one>
</class>
</hibernate-mapping>


我的应用要求是在添加people人物信息的界面,弹出另外一个页面添加人物的picture信息,只有这个页面操作完关闭后,才能返回people添加界面继续操作。
这里在保存picture的时候people还没有生成,people_id就为空了。想法是先保存picture信息,people_id留空,后面保存people信息的时候再更新picture的people_id字段。
但在保存picture的时候报错,保存代码如下:

bean.setTitle(title);
bean.setAddTime(now());
save(bean);


错误提示:

2013-01-17 12:16 INFO  c.j.d.a.f.PictureAction - savePicture()
2013-01-17 12:16 WARN  c.o.x.i.ExceptionMappingInterceptor - null
java.lang.NullPointerException
at com.myproject.common.hibernate3.BaseManagerImpl.save(BaseManagerImpl.java:125) [BaseManagerImpl.class:na]
at com.myproject.manager.impl.PictureMngImpl.savePicture(PictureMngImpl.java:40) [PictureMngImpl.class:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [na:1.5.0_11]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [na:1.5.0_11]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [na:1.5.0_11]
at java.lang.reflect.Method.invoke(Unknown Source) [na:1.5.0_11]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307) [spring-aop-2.5.6.jar:2.5.6]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) [spring-aop-2.5.6.jar:2.5.6]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) [spring-aop-2.5.6.jar:2.5.6]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) [spring-tx-2.5.6.jar:2.5.6]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) [spring-aop-2.5.6.jar:2.5.6]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) [spring-aop-