Hibernate Transaction Example
A Transaction is a sequence of operation which works as an atomic unit. A transaction only completes if all the operations completed successfully. A transaction has the Atomicity, Consistency, Isolation, and Durability properties (ACID). In this tutorial, we are going to talk about the basics of Hibernate Transactions and Sessions.
1. Introduction
1.1 Hibernate
- Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
- Hibernate is a Java based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa. It provides reference implementation of Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling
- A Framework that provides option to map plain old Java objects to traditional database tables with the use of JPA annotations as well as XML based configuration
1.2 Hibernate Transactions
A Transaction is a unit of work in which all the operations must be executed or none of them. To understand the importance of transaction, think of an example which applies on all of us i.e. Transferring Amount from one account to another as this operation includes the below two steps:
- Deduct the balance from the sender’s bank account
- Add the amount to the receiver’s bank account
Now think a situation where the amount is deducted from sender’s account but is not delivered to receiver’s account due to some errors. Such issues are managed by the transaction management where both steps are performed in a single unit. In the case of a failure, the transaction should be roll-backed.
1.2.1 Hibernate Transactions Properties
Every Transaction follows some transaction properties and these are called as ACID properties. ACID stands for Atomicity, Consistency, Isolation, and Durability.
- Atomicity: Is defined as either all operations can be done or all operation can be undone
- Consistency: After a transaction is completed successfully, the data in the datastore should be a reliable data. This reliable data is also called as consistent data
- Isolation: If two transactions are going on the same data then one transaction will not disturb the other transaction
- Durability: After a transaction is completed, the data in the datastore will be permanent until another transaction is going to be performed on that data
1.2.2 Hibernate Transactions Interface
In Hibernate framework, we have Transaction interface that defines the unit of work. It maintains the abstraction from the transaction implementation (JTA, JDBC). A Transaction is associated with Hibernate Session and instantiated by calling the sessionObj.beginTransaction()
. The methods of Transaction interface are as follows:
Name | Description | Syntax |
begin() | It starts a new transaction. | public void begin() throws HibernateException |
commit() | It ends the transaction and flushes the associated session. | public void rollback() throws HibernateException |
rollback() | It rolls back the current transaction. | public void rollback()throws HibernateException |
setTimeout(int seconds) | It set the transaction timeout for any transaction started by a subsequent call to begin() on this instance. | public void setTimeout(int seconds) throws HibernateException |
isActive() | It checks if this transaction is still active or not. | public boolean isActive()throws HibernateException |
wasRolledBack() | It checks if this transaction roll backed successfully or not. | public boolean wasRolledBack()throws HibernateException |
wasCommitted() | It checks if this transaction committed successfully or not. | public boolean wasCommitted()throws HibernateException |
registerSynchronization(Synchronization synchronization) | It registers a user synchronization callback for this transaction. | public boolean registerSynchronization(Synchronization synchronization)throws HibernateException |
1.2.3 Hibernate Transaction Management Basic Structure
This is the basic structure that Hibernate programs should have, concerning Transaction Handling
Transaction transObj = null; Session sessionObj = null; try { sessionObj = HibernateUtil.buildSessionFactory().openSession(); transObj = sessionObj.beginTransaction(); //Perform Some Operation Here transObj.commit(); } catch (HibernateException exObj) { if(transObj!=null){ transObj.rollback(); } exObj.printStackTrace(); } finally { sessionObj.close(); }
Whenever a HibernateException
happens we call rollback()
method that forces the rollback of the transaction. This means that every operation of that specific transaction that occurred before the exception, will be canceled and the database will return to its state before these operations took place.
1.3 Download and Install Hibernate
You can read this tutorial in order to download and install Hibernate in the Eclipse IDE.
1.4 Download and Install MySQL
You can watch this video in order to download and install the MySQL database on your Windows operating system.
Now, open up the Eclipse IDE and let’s see how to implement the transaction management in Hibernate using Annotation!
2. Hibernate Transaction Example
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8, MySQL database and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate on how to create a Java based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, Use default workspace location will be selected. Select the Create a simple project (skip archetype selection) checkbox and just click on next button to proceed.
It will ask you to enter the group and the artifact id for the project. We will input the details as shown in the below image. The version number will be by default 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>HibernateTransaction</groupId> <artifactId>HibernateTransaction</artifactId> <version>0.0.1-SNAPSHOT</version> </project>
We can start adding the dependencies that developers want like Hibernate, MySQL etc. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Database & Table Creation
The following MySQL script is used to create a database called tutorialDb
with table: users
. Open MySQL terminal or workbench terminal and execute the SQL
script.
CREATE DATABASE IF NOT EXISTS tutorialDb; USE tutorialDb; DROP TABLE IF EXISTS users; CREATE TABLE users ( user_id int(11), user_name varchar(15) DEFAULT NULL, created_by varchar(100) DEFAULT NULL, created_date DATE DEFAULT NULL, PRIMARY KEY (user_id) );
If everything goes well, the table will be shown in the MySQL workbench.
3.2 Maven Dependencies
Here, we specify only two dependencies for Hibernate Core and MySQL Connector. The rest dependencies will be automatically resolved by Maven, such as Hibernate JPA and Hibernate Commons Annotations. The updated file will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>HibernateTransaction</groupId> <artifactId>HibernateTransaction</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <!-- Hibernate 4.3.6 Final --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.6.Final</version> </dependency> <!-- Mysql Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
3.3 Java Class Creation
Let’s create the required Java files. Right-click on src/main/java
folder, New -> Package
.
A new pop window will open where we will enter the package name as: com.jcg.hibernate.transaction
.
Once the package is created in the application, we will need to create the model and the implementation classes. Right-click on the newly created package: New -> Class
.
A new pop window will open and enter the file name as Users
. The model class will be created inside the package: com.jcg.hibernate.transaction
.
Repeat the step (i.e. Fig. 11) and enter the filename as HibernateUtil
. The utility class will be created inside the package: com.jcg.hibernate.transaction
.
Again, repeat the step listed in Fig. 11 and enter the file name as AppMain
. The implementation class will be created inside the package: com.jcg.hibernate.transaction
.
3.3.1 Implementation of Model Class
Add the following code to it:
Users.java
package com.jcg.hibernate.transaction; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="users") public class Users { @Id @Column(name = "user_id") private int id; @Column(name = "user_name") private String name; @Column(name = "created_by") private String createdBy; @Column(name = "created_date") private Date createdDate; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } }
3.3.2 Implementation of Utility Class
This class helps in creating the SessionFactory
from the Hibernate configuration file and interacts with the database to perform the INSERT
and UPDATE
operations. Add the following code to it:
HibernateUtil.java
package com.jcg.hibernate.transaction; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateUtil { static Session sessionObj; static SessionFactory sessionFactoryObj; // This Method Is Used To Create The Hibernate's SessionFactory Object private static SessionFactory buildSessionFactory() { // Creating Configuration Instance & Passing Hibernate Configuration File Configuration configObj = new Configuration(); configObj.configure("hibernate.cfg.xml"); // Since Hibernate Version 4.x, ServiceRegistry Is Being Used ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build(); // Creating Hibernate SessionFactory Instance sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj); return sessionFactoryObj; } // Method 1: This Method Used To Create A New User Record In The Database Table public static void createRecord() { Users userObj; try { sessionObj = buildSessionFactory().openSession(); sessionObj.beginTransaction(); for(int j=101; j<=105; j++) { // Creating User Data & Saving It To The Database userObj = new Users(); userObj.setId(j); userObj.setName("Editor " + j); userObj.setCreatedBy("Administrator"); userObj.setCreatedDate(new java.sql.Timestamp(new java.util.Date().getTime())); sessionObj.save(userObj); } // Committing The Transactions To The Database sessionObj.getTransaction().commit(); } catch(Exception sqlException) { if(null != sessionObj.getTransaction()) { System.out.println("\n.......Transaction Is Being Rolled Back......."); sessionObj.getTransaction().rollback(); } sqlException.printStackTrace(); } finally { if(sessionObj != null) { sessionObj.close(); } } System.out.println("\n.......Records Saved Successfully In The Database.......\n"); } // Method 2: This Method Used To Update A User Record In The Database Table public static void updateRecord() { Users userObj; int user_id = 103; try { sessionObj = buildSessionFactory().openSession(); sessionObj.beginTransaction(); userObj = (Users) sessionObj.get(Users.class, new Integer(user_id)); // This line Will Result In A 'Database Exception' & The Data Will Rollback (i.e. No Updations Will Be Made In The Database Table) userObj.setName("A Very Very Long String Resulting In A Database Error"); // Committing The Transactions To The Database sessionObj.getTransaction().commit(); } catch(Exception sqlException) { if(null != sessionObj.getTransaction()) { System.out.println("\n.......Transaction Is Being Rolled Back......."); sessionObj.getTransaction().rollback(); } sqlException.printStackTrace(); } finally { if(sessionObj != null) { sessionObj.close(); } } } }
3.3.3 Implementation of Main Class
Add the following code to it:
AppMain.java
package com.jcg.hibernate.transaction; public class AppMain { public static void main(String[] args) { HibernateUtil.createRecord(); HibernateUtil.updateRecord(); System.exit(0); } }
3.4. Hibernate Configuration File
To configure the Hibernate framework, we need to implement a configuration file i.e. hiberncate.cfg.xml
. Right-click on src/main/resources
folder, New -> Other
.
A new pop window will open and select the wizard as an XML file.
Again, a pop-up window will open. Verify the parent folder location as HibernateTransaction/src/main/resources
and enter the file name as hibernate.cfg.xml
. Click Finish.
Once the file is created, we will include the database configuration and mapping class details. Add the following code to it:
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- SQL Dialect --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Database Connection Settings --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tutorialDb</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password"></property> <!-- Echo All Executed SQL To Console --> <property name="show_sql">true</property> <!-- Specifying Session Context --> <property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property> <!-- Mapping With Model Class Containing Annotations --> <mapping class="com.jcg.hibernate.transaction.Users" /> </session-factory> </hibernate-configuration>
Notes:
- Here, we instructed Hibernate to connect to a MySQL database named
tutorialDb
and the Mapping classes to be loaded - We have also instructed Hibernate framework to use
MySQLDialect
i.e. Hibernate will optimize the generated SQL statements for MySQL - This configuration will be used to create a Hibernate
SessionFactory
object show_sql
tag will instruct the Hibernate framework to log all theSQL
statements on the console
4. Run the Application
To run the Hibernate application, Right-click on the AppMain
class -> Run As -> Java Application
.
5. Project Demo
Executing the AppMain
class, you will see the records created in the users
table. Developers can debug the example and see what happens in the database after every step. Enjoy!
Here after running the UPDATE
operation we get the following output:
Below is the snapshot of the MySQL Database after the execution of the above program.
Users Table
That’s all for this post. Happy Learning!!
6. Conclusion
In this topic, developers learned about Transactions, Consistency, Isolation, and Durability. Developers now know that Hibernate relies on the database concurrency control mechanism but provides better isolation guarantees in a transaction. That’s all for Hibernate Transaction tutorial and I hope this article served you whatever you were looking for.
7. Download the Eclipse Project
This was an example of Hibernate Transaction.
You can download the full source code of this example here: Hibernate Transaction
For reading a record from DB, is it required/recommended to start a transaction?
If yes, won’t it make more work to manage the transaction? Rollback after reading is done if not then it will cause connection leak. Keeping transaction open for long can cause unnecessary resource usage.