MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

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

[Close]

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 create CRUD in Hibernate

In this article we will learn how to perform crud operations in Hibernate in Java.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Hibernate is used for Object Relational Mapping between database and Java class objects. It defines objects to communicate with database. These objects are used to create database tables and schemas and also perform database tables operations like CRUD operation i.e. Create, Delete and Update table records.

CRUD Operations with Hibernate in Details:

There are many way to perform CRUD operation in Hibernate. One way is using Session class object of the Hibernate package. There is set of methods of Session class, which helps to perform CRUD operation on a database table using Hibernate as:

  • save()
  • get()
  • delete()
  • and update()

These four methods of Session class are used as following to perform CRUD operations respectively:

  • Creating a record into database table using save() method:
  • Create a bean class object and assign this object as an argument into Session class method save():
new Session().save(<bean-class-object);

Ex: UserDetails obj = new UserDetails();
session.save(obj);

Above example defines a bean class object “obj” of “UserDetails” class and assign this object as an argument into save() method of “Session” class.

Fetch a record from database table using primary key record (defined):

To get a record from database table, we are required to specify a primary key record as a where clause condition that will be applied on the database table specified into first argument of the method:

new Session.(<Bean-class-object>, <primary-key-record>);

get() method take two parameter, where first parameter take bean class object as an argument and second argument is the primary key record that is applied on the table as a where clause to fetch records from the database table.

Ex. UserDetails obj = (UserDetails) session.get(UserDetails.class, 6);

Above example defines a “UserDetails” bean class object and assigned it as first argument and second argument is primary key record that is applied as where clause condition on “UserDetails” database table specified using first argument of get() method.

To perform delete operation, there is a delete() method that accept bean class object as an argument as:

new Session().delete(<bean-class-object>);

Ex. UserDetails obj = (UserDetails) session.get(UserDetails.class, 6);
session.delete(obj);

Above example calls a method delete() that accepts an object of UserDetails class. This object is assigned to UserDetails referenced data fetched from the database table according to specified primary key record.

To update a record of the database table, we are required to access this record from the database table and update this access record and assign this bean updated bean class object to update() method of the Session class as:

new Session().update(<bean-class-object>);

Ex.: UserDetails obj = (UserDetails) session.get(UserDetails.class, 5);
obj.setUserName(“Update Name”);
session.update(obj);

Above example access the data from the database table at primary key record “5” and update its data using its setter() method and now call method update() and assign this UserDetails bean class object as an argument.

Let’s go with an example that performs CRUD operation using four different classes to perform these four actions with a bean class that creates a database table.

Listing 1 defines “UserDetails.java” bean class as:

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 int userId;
	private String userName;
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
}

Listing 1 defines a “UserDetails.java” java bean class that defines two class member variables as “userId” of integer type that is defined as a primary key of the database table and will be assigned to auto-generated values and “userName” of String type with its getter() and setter() methods.

Now, let’s define AddRecords.java java application class into Listing 2 as:

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){
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();		
		//To create data
		for(int i = 0; i < 10; i++){
			UserDetails user = new UserDetails();
			user.setUserName("user" + i);
			session.save(user);
		}				
		session.close();
	}
}

Listing 2 defines AddRecords.java java application class that defines a main() method. This method defines hibernate connection to communicate with database “MySql” using SessionFactory class and define a session using Session class.

Once these configuration settings are done, create “UserDetails” bean class object inside “for” loop that loops for ten times and save each record into database table at the iteration of each loop. This record is being saved using save() method of the Session class. Once “for” loop terminates, session is closed using close() method of the Session class.

To fetch a record form the database, we define another class named GetRecords.java in Listing 3 as:

Listing 3: GetRecords.java

package com.test.crud;
	import org.hibernate.Session;
	import org.hibernate.SessionFactory;
	import org.hibernate.cfg.Configuration;

	public class GetRecords {
		public static void main(String[]args){
			SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			
			//To fetch data
			UserDetails obj = (UserDetails) session.get(UserDetails.class, 6);
			System.out.println("UserName : " + obj.getUserName() );
			session.getTransaction().commit();
					
			session.close();
		}
	}

Listing 3 defines GetRecords.java java application class that defines a main() method. This method defines hibernate configuration settings with “MySql” database and also defines a session object using Session class. This session object call a get() method of the Session class to fetch a record from the database table, this method accepts two arguments. The first argument accepts the bean class (“UserDetails.class”) and the second argument accepts the primary key records that will match with the database table primary key record.

Now let’s define a java application class DeleteRecords.java in Listing 4 as:

Lisitng 4: DeleteRecords.java

package com.test.crud;
	import org.hibernate.Session;
	import org.hibernate.SessionFactory;
	import org.hibernate.cfg.Configuration;

	public class DeleteRecords {
		public static void main(String[]args){
			SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			
			//To delete data
			UserDetails obj = (UserDetails) session.get(UserDetails.class, 6);
			session.delete(obj);
					
			session.close();
		}
	}

Listing 4 defines a DeleteRecords.java application class that defines a main() method. This main() method defines a hibernate configuration setting for “MySql” database and also define a session object of Session class. This session object calls the delete() method of the Session class that accepts the bean class object as an argument and removes the record from the database table on the specified primary key record. Once the records has been removed from the database table, the session is closed using close() method of the Session class.

Now, let’s define UpdateRecords.java class in Listing 5:

Listing 5: UpdateRecords.java

package com.test.crud;
	import org.hibernate.Session;
	import org.hibernate.SessionFactory;
	import org.hibernate.cfg.Configuration;

	public class UpdateRecords {
		public static void main(String[]args){
			SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			
			//Update data record of table
			UserDetails obj = (UserDetails) session.get(UserDetails.class, 6);
			obj.setUserName("Updated UserName");
			session.update(obj); 
					
			session.close();
		}
	}

Listing 5 defines a UpdateRecords.java application class that defines the main() method. This method declares hibernate configuration setting for “MySql” database and also defines session object of Session class. An update() method is called of the Session class using session object that accepts the bean class object (“UserDetails” class object) as an argument. The bean class object get the record from the database using the get() method and use the setter method setUserName() to update existing record of the database table.

Required Tools and applications:

To run this example, we are required set of tools and applications and a set of jar file listed:

  • Eclipse IDE (Eclipse Juno)
  • JDK Environment (JDK 7)
  • Set of Hibernate Jar files (Hibernate 3) as shown in Figure 1:
Set of Hibernate 3 Jar file

Figure 1: Set of Hibernate 3 Jar file

Directory Structure:

Eclipse IDE creates a directory structure for the hibernate application as shown in Figure 2:

HibernateCrudOperation application directory structure created by Eclipse IDE

Figure 2: HibernateCrudOperation application directory structure created by Eclipse IDE

Figure shows the directory structure created by the Eclipse IDE for the hibernate application.

While we execute this application, this shows results in console as shown in these 4 figures as follows:

Inserting 10 records into the database table UserDetails

Figure 3: Inserting 10 records into the database table UserDetails

After executing AddRecord java class file, there are ten rows, added into database table UserDetails as shown into figure Figure 4:

 10 rows added into the database table UserDetails

Figure 4: 10 rows added into the database table UserDetails

Now, let’s run GetRecords java class the fetch record from database table UserDetails at row 6:

Fetching a single records from the database table UserDetails on primary key record 6

Figure 5: Fetching a single records from the database table UserDetails on primary key record 6

To delete a row 6 from database table UserDetails, where primary key record is 6, is deleted from the database table UserDetails as Figure 6 shows:

Deleting a single row from the database table UserDetails on primary key record 6

Figure 6: Deleting a single row from the database table UserDetails on primary key record 6

After deleting a row, where primary key record is 6, is removed from the database table UserDetails, the database table status is as shown figure 6:

Table status after deleting a record from the table UserDetails

Figure 7: Table status after deleting a record from the table UserDetails

To update a record into the database table UserDetails, where primary key “userId” record is 5, run the java class UserDetails that update the “userName” to “Updated Name”:

Updating a single row record into the database table at primary key record 5

Figure 8: Updating a single row record into the database table at primary key record 5

After update process is done, the status of the table is shown into Figure 8:

Update is being displayed at row 5 in the database table UserDetails

Figure 9: Update is being displayed at row 5 in the database table UserDetails

Conclusion:

In this article, we learn about the CRUD operations that are performed with hibernate. We also learned the way of defining CRUD operations. Session was used to define CRUD operation on hibernate in this article.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[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