Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to use Transient, Persistence and Detached Objects in Hibernate

In this article, we will learn what are the transient, persistence and detached objects and also how do we use it with hibernate

While an entity class is created to create a database table or an entity, it is done by making an instance of the entity class and by assigning this instance to the session instance, database table schema is added or updated into the database and a table entry is made. Once the session transaction is saved, it is required to release the entity class instance. These three states of object are classified into their specific categories as Transient, Persistence and Detached object. This article will dictate these all three states of an entity class and will go with an example on this.

Transient, Persistence and Detached Objects in Detail:

Once an entity class has been created to create a database entity or table, it is required to connection with the hibernate and database using SessionFactory and its set of classes. Once the connection configuration is done, we are required to create an instance of the entity class. This state of instance is known as Transient Object.To save the entity class instance into the database, we are required to create a Session class instance that will use the method save() to save the entity class instance into the database. This configuration of the entity class instance is known as Persistence Object.It is necessary to close the session instance after performing the database task. Once a session instance is closed, the state of entity class instance is set to Detached Object.

Let’s go with an example that will dictate the use of transient, persistence and detached object as started with Listing 1:

Listing 1: UserDetails.java

package com.test.crud;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
public class UserDetails {
	@Id @GeneratedValue(strategy=GenerationType.AUTO)
	private intuserId;
	private String userName;
	public intgetUserId() {
		return userId;
	}
	public void setUserId(intuserId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
}

Listing 1 defines a java class UserDetails.java that defines two class variables with its getter() and setter() methods. This class is an entity class that will be used to create an entity table into the mysql database. There are set of annotations are defined as “@Entity” that defines an entity class for database, this annotation is defined into the the package class name “javax.persistence.Entity” and annotation “@Id @GeneratedValue(strategy=GenerationType.AUTO)” is defined into the package class name “javax.persistence.GeneratedValue”, “javax.persistence.GenerationType” and “javax.persistence.Id”.

Now let’s create an instance into another java class file that will create a transient object and make object a persistence object and once this object is saved into the database, this object need to set as detached object as shown into the listing 2:

Listing 2: AddRecords.java


package com.test.crud;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class AddRecords {
	public static void main(String[]args){
		SessionFactorysessionFactory = new Configuration().configure().buildSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		//To create data
		for(int i = 0; i < 10; i++){
			UserDetails user = new UserDetails();//Creating Transient Object
			user.setUserName("user" + i); //Setting up values to the transient object
			session.save(user);//Updating the transient object to persistnence object
		}
		
		session.getTransaction().commit();
		session.close(); //Session is closed
	}
}

Listing 2 defines another java class “AddRecords.java” that defines the main() method and defines a SessionFactory instance into this method. This instance is used to create a Session class instance that will be used to make a transient object to persistence object.Comment lines of Listing 2 is highlighted that shows the dependent code that creates a transient object, persistence object and also shows the way of closing a created session using close() method of Session class.Once the session is ended, the persistence object set to detached object and its state is treated as transient object as at initial stage.

Once a persistence object is set to detached, it is required to save once again to make it persisted. But it’s setter values remain persist into this object, hence it’s not remain transient as it is created at its initial level and is called detached object.

Let’s define one more listing that will define the main use of session maintenance, if there is response is user input dependent, in this way an opened session should be closed as soon as possible and an action should be continued with the new session for the access data from the previous session and its result is updated in this new session as:

Listing 3: GetUpdateRecord.java

package com.test.crud;

	import org.hibernate.Session;
	import org.hibernate.SessionFactory;
	import org.hibernate.cfg.Configuration;

	public class GetUpdateRecords {
		public static void main(String[]args){
			SessionFactorysessionFactory = new Configuration().configure().buildSessionFactory();
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			
			//To fetch data
			UserDetailsobj = (UserDetails) session.get(UserDetails.class, 2);
			System.out.println("UserName : " + obj.getUserName());
			
			session.getTransaction().commit();
			session.close();
			
			session = sessionFactory.openSession(); //Open an instance of Session class.
			session.beginTransaction();
			
			obj.setUserName("Update Name"); //Update Database Record using setter() method.
			
			//To Update data
			session.update(obj); //Update the data into the database using update() metod of the session class.
			
			session.getTransaction().commit();
			session.close();
		}
	}

Listing 3 defines one more java class GetUpdateRecords.java that defines a main() method. This method defines a session class instance and use this session fetch the record from the database and close this session instance using the close() method of the Session class. Now update the database record using the setter() method of the class and assign this updated record the database table using update() method of the new session class instance.Once the record is updated into the database, the session instance should be closed once again using the close() method of the session class.

Now, Let’s define a hibernate configuration file that will be used to configure the hibernate database connecton and few set of setting that will be used, while configuring database as:

Listing 4: hibernate-cfg.xml


<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
	<!-- Database Connection Settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<!-- JDBC Connection Pool (Use the built-IN) -->
<property name="connection.pool_size">1</property>

<!-- Diable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Database Schema Modification Type -->
<property name="hbm2ddl.auto">update</property>

<!-- Database Dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Hibernate Class Mapping -->
		<mapping class = "com.test.crud.UserDetails"/>
	</session-factory>
</hibernate-configuration>

Listing 4 defines a hibernate configuration file to setup the database connection with the database “MySql” with the specified username, password and a database name. We also define the database schema to be updated everytime, while we are making a session updates into the database or to add a record into the database.

Required Tools and Applications:

We are required to have set of tools and application listed to configure and run this given example into this article:

  • Eclispe IDE (Eclipse Juno)
  • JDK Run time environment (JDK 1.7)
  • MySql Database
  • Set of hibernate jar files and a MySql database connector as shown into the figure 1:
List of required jar files

Figure 1: List of required jar files

Directory Structure Created by Eclipse:

Directory Structure of application

Figure 2: Directory Structure of application

Figure 2 shows the directory structure created by eclipse ide for hibernate application.

While we run this application using AddRecords.java java class file, it adds a record into the database as shown into Figure 3 as:

Adding records into the database table UserDetails

Figure 3: Adding records into the database table UserDetails

To update a record of id record 2, GetUpdateRecords.java class file is executed as shown in figure 4 and 5:

Get the data from table that will updated to Updated Name

Figure 4: Get the data from table that will updated to “Updated Name”

Fetch the updated record from the database table UserDetails as Updated Name

Figure 5: Fetch the updated record from the database table UserDetails as “Updated Name”

Figure 5 listed the name at the record number that was updated using the java class file GetUpdatedRecords.java.

Conclusion:

In this article, we came to know about the stages of an object of entity class that is being created into the java application or java web application and also learn the way of changing these object state from one object to another while it is assigned to Session class object and released from the session object. We also went through an example that shows this configuration of changing state change.

See also



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login