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

拈花ヽ惹草 提交于 2019-12-22 09:03:51

问题


i have a self join employees entity class with id,name and ref columns that has relation with it self. i want to create new instance of that and persist it to db.

at first i created an instance of Employee class and named it manager. then i fetched a record from Employee table with these values: Id = 1, Name = "A", RefId = null and set those values to manager object. after that i created an instance of Employee class again
and set it's properties value like this: emp.Name = "B", emp.Ref = manager. finally i persisted it by using base.Add(resource) method. at that time Nhibernate raised the following error: "object references an unsaved transient instance save the transient instance before flushing".

this is mapping file contents:

<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 to solve this error. thx


回答1:


Let's say Entity 1 is the existing record in the database, and Entity 2 is the new record that you are trying to create that has a reference to Entity 1.

Hibernate is telling you that the new entity (entity 2) you are saving has a reference to entity 1 (the one from the database), and that entity 1 has unsaved changes that must be saved before it can save entity 2. The easiest thing to do is save entity 1 first, then save entity 2. But, I think the real issue is how you are getting an instance of Entity1.

You say that you create and instance of employee, then name it manager, then fetch a record from the employee table. If you are trying to update the existing record from the table, why don't you fetch the entity first, then edit it? Why are you instantiating an object at all? The other thing I wasn't sure about was whether the relationship between the objects was bi-directional. That is, Entity 1 has an FK to Entity 2 AND ALSO Entity 2 has an FK to Entity 1. If this is the case, you need to make sure you assign your "Ref" property twice. Entityy1.Ref = Entity2 AND ALSO Entity2.Ref = Entity1.



来源:https://stackoverflow.com/questions/6596289/object-references-an-unsaved-transient-instance-save-the-transient-instance-befo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!