org.hibernate.transientobjectexception
In this section, you will learn org.hibernate.transientobjectexception it's cause and solution.
But before discussing it further, you need to know about transient object :
A new persistence class instance, which is not related to a Session and has not contained any value representing row of a database table and also have not contained any identifier value, is considered as transient by Hibernate.
Student student=new Student(); student.setName("Rajesh"); // student is in transient state
You can convert transient instance into persistence by associating it with a Session as follows :
Long id = (Long) session.save(student); // person is now in a persistent state
transientobjectexception
The transientobjectexception is thrown when a transient instance is passes to a Session method that expects a persistent instance.
Let us take a simple example :
X is referring to Y using a primary key column of yId of Y.
The mapping of X is something like this :
<class name="net.roseindia.X" table="X" > <id name="xId" type="java.lang.Long"> <property name="xId" column="x_id" /> </id> ................. ................. <many-to-one name="yId" class="net.roseindia.Y" fetch="select"> <column name="y_id" not-null="true" /> </many-to-one> ................ ................
Now, we want to persist the value of foreign key in X. You have to make sure that instance Y is persistent not transient.
But if you try something like this :
X x = new X(); Y y = new Y(); x.setY(y); .......... .......... session.save(x);
This will throw org.hibernate.transientobjectexception :
solution
Since Y is in transient state which is the root cause of the problem. To make instance Y persistent, you need to bind y to the session. You can do it like this :
X x = new X(); Y y = session.get(Y.class, new Long(1)); x.setY(y); ......................... ......................... session.save(x);
The above code will run smoothly without throwing org.hibernate.transientobjectexception .