Techspace

IT happens only in IT

org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance before flushing:

I was getting this error today.
org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance before flushing:This is the problemTable A was referring to the talbe B using a foreign key

hbm.xml for A looked like this

<class name=”com.xxx.A” table=”A” schema=”TESTSCHEMA”>
<id name=”aId” type=”java.lang.Long”>
<column name=”A_ID” precision=”29″ scale=”0″ />
</id>…………………..
some more mapping elements
…………………..
…………………..
<many-to-one name=”bId” class=”com.xxx.B” fetch=”select”>
<column name=”B_ID” precision=”29″ scale=”0″ />
</many-to-one>

…………………..

I just want to save A with some new value and A will refer to B using some foreign key. But in my transaction I am not going to change B and save the changes. Therefore the many-to-one mapping above is wrong. It does not tell hibernate that class b is immutant. That is it is not going to change. Hibernate thinks that the referred table is not saved therefore it complains and says

org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance before flushing:

Please note that in this case B is transient object. If you don’t really want to save the value of B(transient object) in A , then to get rid of this problem change the many-to-one mapping as

update=”false” insert=”false” fetch=”select”>

But if you want to save the value of B then see my other post

That is, tell hibernate that you are not going to change the values of B, you are just fetching it.

 

January 14, 2008 - Posted by Paras | Hibernate | , | 6 Comments

6 Comments »

  1. Hi man you made my day ….
    Thanks

    Comment by David | September 30, 2008 | Reply

  2. Excellent post. Keep up the good work.

    Comment by small | October 8, 2008 | Reply

  3. Hi,

    Thank you very much, you solved my problem ;-)

    Have a nice day,
    Khalid

    Comment by Khalid | February 3, 2009 | Reply

  4. Thanks for sharing, one quick clarification. I was not able to insert the data for mapped columns when flags are set to false. But when I set flags to true, everything works well.

    Comment by Sathish | August 11, 2009 | Reply

    • Hi Sathish,
      Yes when you set the flag to true Hibernate will do the inserts for those mapped columns. setting fields to false tells the hibernate that this fields are read only and hibernate should not update them.

      Comment by Paras | August 12, 2009 | Reply

  5. Thanks.. :)

    Comment by Yogi | September 16, 2009 | Reply


Leave a comment