Hibernate: insert into users (name, room_id) values (?, ?) select scope_identity() org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: po.Room at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:219) at org.hibernate.type.EntityType.getIdentifier(EntityType.java:397) at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:242) at org.hibernate.type.TypeFactory.findDirty(TypeFactory.java:563) at org.hibernate.persister.entity.AbstractEntityPersister.findDirty(AbstractEntityPersister.java:3071) at org.hibernate.event.def.DefaultFlushEntityEventListener.dirtyCheck(DefaultFlushEntityEventListener.java:472) at org.hibernate.event.def.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:197) at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:120) at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:196) at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at dao.imp.UsersDAL.SaveUser(UsersDAL.java:22)
at dao.imp.test.main(test.java:21)
这句异常的意思是:我们在使用一个临时的对象room,按常理我们应先保存room,然后保存users信息。解决此问题我们可以采取以下2种方式将room列入session保持其持久化状态:
先save room再save users,即保证users与room共用一个session,因为dal中代码已封装好,因此采用第二种方式即cascade关键字
使用cascade关键字(取值:none、save-update、all、delete)
按照以上方法配置过后出现
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. Hibernate: insert into room (name) values (?) select scope_identity() Exception in thread "main" java.lang.NullPointerException at dao.imp.RoomDAL.SaveRoom(RoomDAL.java:20)
at dao.imp.test.main(test.java:23)
配置方法如下: <class name="po.Users" table="users"> <id name="id" type="integer"> <column name="id"></column> <generator class="native"></generator> </id> <property name="name" type="string"> <column name="name" not-null="true" length="30"></column> </property> <many-to-one name="room" class="po.Room" cascade="all"> <column name="room_id"></column> </many-to-one> </class>
</> |