Techspace

IT happens only in IT

org.hibernate.TransientObjectException Revisited

This is continuation of my earlier post on org.hibernate.TransientObjectException. Let me write the scenario again

<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>

…………………..

A is referring to B using a primary key column of bId of B.

In that post I have mentioned that if B is a transient object and you don’t want to persist the value of B to A then just tell the hibernate to ignore that value by saying
update=”false” insert=”false” in the many to one mapping.

But what if you want to persist the value of foreign key in A.

Then the approach is different. You have to make sure that instance B is persistent not transient.

That is if your code says something like

A a = new A();
B b = new B();
a.setB(b);
…..
…..

session.save(a);

you are in trouble. Because B is in transient state. You have to attach b to the session.
There may be other ways of attaching this transient object to session. The approach I am following is simple. I am reading the value of B from the database using Hibernate. That way, hibernate attaches B to session and it is then a persistent object.

That is I do something like

A a = new A();
B b = session.get(B.class, new Long(1));
a.setB(b);
…..
…..

session.save(a);

I won’t get any exception because this time there is no transient object to save. All the objects are persistent.

Powered by ScribeFire.

January 28, 2008 Posted by | Hibernate | 13 Comments

   

Follow

Get every new post delivered to your Inbox.