object references an unsaved transient instance -

2019-01-01 01:42发布

I receive following error when I save the object using Hibernate

object references an unsaved transient instance - save the transient instance before flushing

23条回答
公子世无双
2楼-- · 2019-01-01 01:48

This happens when saving an object when Hibernate thinks it needs to save an object that is associated with the one you are saving.

I had this problem and did not want to save changes to the referenced object so I wanted the cascade type to be NONE.

The trick is to ensure that the ID and VERSION in the referenced object is set so that Hibernate does not think that the referenced object is a new object that needs saving. This worked for me.

Look through all of the relationships in the class you are saving to work out the associated objects (and the associated objects of the associated objects) and ensure that the ID and VERSION is set in all objects of the object tree.

查看更多
姐姐魅力值爆表
3楼-- · 2019-01-01 01:48

If your collection is nullable just try: object.SetYouColection(null);

查看更多
冷夜・残月
4楼-- · 2019-01-01 01:49

I faced this exception when I did not persist parent object but I was saving the child. To resolve the issue, with in the same session I persisted both the child and parent objects and used CascadeType.ALL on the parent.

查看更多
裙下三千臣
5楼-- · 2019-01-01 01:50

This occurred for me when persisting an entity in which the existing record in the database had a NULL value for the field annotated with @Version (for optimistic locking). Updating the NULL value to 0 in the database corrected this.

查看更多
梦寄多情
6楼-- · 2019-01-01 01:52

One other possible reason: in my case, I was attempting to save the child before saving the parent, on a brand new entity.

The code was something like this in a User.java model:

this.lastName = lastName;
this.isAdmin = isAdmin;
this.accountStatus = "Active";
this.setNewPassword(password);
this.timeJoin = new Date();
create();

The setNewPassword() method creates a PasswordHistory record and adds it to the history collection in User. Since the create() statement hadn't been executed yet for the parent, it was trying to save to a collection of an entity that hadn't yet been created. All I had to do to fix it was to move the setNewPassword() call after the call to create().

this.lastName = lastName;
this.isAdmin = isAdmin;
this.accountStatus = "Active";
this.timeJoin = new Date();
create();
this.setNewPassword(password);
查看更多
公子世无双
7楼-- · 2019-01-01 01:54

I think is because you have try to persist an object that have a reference to another object that is not persist yet, and so it try in the "DB side" to put a reference to a row that not exists

查看更多
登录 后发表回答