The object refers to an unsaved transient instance, storing a temporary instance before flushing

I have my own class of employee entities with identifiers, names, and links that are relevant to it. I want to create a new instance of this and save it in db.

I first created an instance of the Employee class and called it the manager. then I extracted an entry from the Employee table with these values: Id = 1, Name = "A", RefId = null and set these values ​​for the manager object. after that I created an instance of the Employee class again
and set the property value as follows: emp.Name = "B", emp.Ref = manager. finally, I saved it using the base.Add (resource) method. at that time, Nhibernate raised the following error: "the object refers to an unsaved transient instance, storing a temporary instance before flushing."

this is the contents of the mapping file:

<class name="Employee" table="Employee" schema="dbo" optimistic-lock="none" lazy="true"> <id name="Id" access="property" column="Id"> <generator class="identity" /> </id> <property name="Name" type="String" column="Name" length="50" /> <property name="RefId" type="Int64" column="RefId" insert="false" update="false"/> <many-to-one name="Ref" class="Employee" column="RefId" not-null="false" fetch="select" /> class> 

please help me resolve this error. THX

+4
source share
1 answer

Suppose Entity 1 is an existing entry in the database, and Entity 2 is the new entry you are trying to create that has a link to Entity 1.

Hibernate tells you that the new object (object 2) that you save has a reference to object 1 (that of the database), and that object 1 has unsaved changes that must be saved before it can save object 2. The easiest - first save object 1, and then save object 2. But I think the real problem is how you get an instance of Entity1.

You say that you create an employee instance, and then call it the manager, and then retrieve the record from the employee table. If you are trying to update an existing record from a table, why don’t you first get the object, but change it? Why are you creating an instance of the object at all? Another thing is that I was not sure whether the connection between the objects was bidirectional. That is, Entity 1 has an FK for object 2 AND ALSO Object 2 has an FK for Entity 1. If so, you need to make sure that you set the Ref property twice. Entityy1.Ref = Entity2 AND ALSO Entity2.Ref = Entity1.

+3
source

All Articles