Apr
30
2015

CascadeType Example in hibernate and org.hibernate.TransientObjectException

Hi in this post of hibernate i will describe one more feature of hibernate. Let say we have some one to many realtion like below. In this relationship Course have many department. Let say each couurse have fifteen deparment. Then whenever i save a new course entity i need to save all the related deparment in that session.

many to one relatioship dept and course

many to one relatioship dept and course

If we don’t save all the associated object then hibernate will throw an exception.

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

To escape from this exception hibernate provide a feature of CascadeType which tell hibernate that whenever any operation is done on a object , same operation will be performed on all the associated object . In this case when any operation will be performed on course object then same operation will be performed on associated department objects.

Here is simple example of CascadeType

Department.java

Course.java

Here @OneToMany have parameter cascade associated with it .CascadeType is enum type that have following values 

*cascade=CascadeType.ALL
* cascade=CascadeType.DETACH
* cascade=CascadeType.MERGE
* cascade=CascadeType.PERSIST
* cascade=CascadeType.REFRESH
* cascade=CascadeType.REMOVE

CascadeType.java

When we run this program then following are queries that run.

Hibernate: insert into Course (courseName) values (?)
Hibernate: insert into Department (course_id, deptName) values (?, ?)
Hibernate: insert into Course_Department (Course_id, department_id) values (?, ?)

Here you can see even if we are just saving course object all the object associated with course get saved automatically with in same session.

If we remove Cascade parameter from @OneToMany(cascade=CascadeType.ALL) then hibernate will throw following exception.

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

This is all in this post. In next post i will explain about @NotFound annotation.

About the Author: devender kumar

java/j2EE developer

Comments are closed.