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 Paras | Hibernate | | 4 Comments

4 Comments »

  1. I’m doing just what you say, but I still get the transientobjectexception… It is very strange.

    Comment by Dave Bates | March 26, 2008 | Reply

  2. Sorry should have finished my previous post. the update=”false” insert=”false” works just fine, but why is it required when I have just loaded the value of the many to one column from the database? Should be the same sessions right? Right in the same method… And there are other very similar properties (i am initializing the same way) that don’t have the problem. That is what is strange.

    Comment by Dave Bates | March 26, 2008 | Reply

  3. what happens if A and B are new objects

    that is if B is not existing in the DB.

    Is there a strategy there

    Comment by Niraj | May 7, 2008 | Reply

  4. Hi paras,
    could you help me
    how to do this with JPA
    A a = new A();
    B b = session.get(B.class, new Long(1));
    a.setB(b);
    …..
    …..

    session.save(a);
    TIA
    kirti

    Comment by Anand | January 7, 2009 | Reply


Leave a comment