org.hibernate.TransientObjectException Revisited
January 28th, 2008
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.
Filed under: Hibernate

4 Comments Add your own
1.
Dave Bates | March 26th, 2008 at 4:36 pm
I’m doing just what you say, but I still get the transientobjectexception… It is very strange.
2.
Dave Bates | March 26th, 2008 at 4:58 pm
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.
3.
Niraj | May 7th, 2008 at 6:19 pm
what happens if A and B are new objects
that is if B is not existing in the DB.
Is there a strategy there
4.
Anand | January 7th, 2009 at 12:55 pm
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
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed