父类中有一个列表List。保存父项后,已添加或更改的子项应通过hibernate保存/更新。
我找到了很多解释,但是,我只是没有使它起作用。
Parent.class试试A
@Entity public class Parent { // id and other attributes @OneToMany(mappedBy = "parent") @org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.ALL) protected List<child> children;
Parent.class试试B
@Entity public class Parent { // id and other attributes @OneToMany(mappedBy = "parent", cascade = { javax.persistence.CascadeType.ALL }, orphanRemoval = true) @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH, org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.REPLICATE, org.hibernate.annotations.CascadeType.LOCK, org.hibernate.annotations.CascadeType.DETACH }) protected List<child> children;
孩子被添加到新的父母。之后两者都保存
sessionFactory.getCurrentSession().saveOrUpdate(parent);
但是在冲洗时,出现以下错误:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: de.pockettaxi.backend.model.ride.RideSingle at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:243) at org.hibernate.type.EntityType.getIdentifier(EntityType.java:456) at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:265) at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:275) at org.hibernate.type.TypeHelper.findDirty(TypeHelper.java:295) at org.hibernate.persister.entity.AbstractEntityPersister.findDirty(AbstractEntityPersister.java:3378) at org.hibernate.event.def.DefaultFlushEntityEventListener.dirtyCheck(DefaultFlushEntityEventListener.java:520) at org.hibernate.event.def.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:230) at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:154) at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:219) at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
有人看到我的错误吗?
非常感谢!!
我想如果您从第一条评论中回答这个问题,我们就会遇到这种情况:
在那种情况下,hibernate只是将保存或更新级联到子级,但是由于它们尚未持久,因此无法保存或更新。现在,Hibernate只是说“我无法更新非持久性实体”
一句话:Hibernate只级联它发出的级联。在这种情况下,您将发出一个 “ SAVE_UPDATE” ,然后将其级联到子级。我想您希望Hibernate变得聪明,并为这里的孩子们坚持下去。但这不是Hibernate在这里工作的方式,我之前也遇到过类似的情况。有点令人困惑,但是如果您一旦了解了级联的工作原理,就会看到这种情况。