🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
ession.beginTransaction in Hibernate 6 with Java 21. We'll create a simple application that performs database operations within a transaction and demonstrates how to begin, commit, and roll back a transaction.Introduction
Transactions in Hibernate allow multiple operations to be grouped into a single unit of work. Using session.beginTransaction, you can start a new transaction, ensuring that all operations within the transaction are either completed successfully or rolled back in case of an error.
In this tutorial, we will:
- Set up a Maven project with Hibernate and an H2 database dependency.
- Configure Hibernate.
- Create an entity class (
User). - Implement a method to perform database operations within a transaction.
- Demonstrate transaction management with a sample application.
Step 1: Set Up Your Project
1.1 Create a Maven Project
Open your IDE and create a new Maven project.
1.2 Add Dependencies
Update your pom.xml file to include the necessary dependencies for Hibernate and H2 (an in-memory database for simplicity).
<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>com.example</groupId> <artifactId>hibernate-transaction-example</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- Hibernate ORM --> <dependency> <groupId>org.hibernate.orm</groupId> <artifactId>hibernate-core</artifactId> <version>6.4.0.Final</version> </dependency> <!-- H2 Database --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>2.1.214</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.10.1</version> <configuration> <source>21</source> <target>21</target> </configuration> </plugin> </plugins> </build> </project> 1.3 Configure Hibernate
Create a file named hibernate.cfg.xml in the src/main/resources directory to configure Hibernate. This file contains the database connection settings and Hibernate properties.
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property> <property name="hibernate.connection.driver_class">org.h2.Driver</property> <property name="hibernate.connection.url">jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> </session-factory> </hibernate-configuration> Explanation:
hibernate.dialectspecifies the SQL dialect to be used.hibernate.connection.driver_classspecifies the JDBC driver class.hibernate.connection.urlspecifies the JDBC URL for the database connection.hibernate.connection.usernameandhibernate.connection.passwordspecify the database credentials.hibernate.hbm2ddl.autospecifies the schema generation strategy.hibernate.show_sqlspecifies whether to show SQL statements in the logs.
Step 2: Create the Entity Class
Create an entity class User that will be mapped to a table in the database. This class uses annotations to define the entity and its fields.
package com.example.entity; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // Getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } Explanation:
- The
@Entityannotation specifies that the class is an entity and is mapped to a database table. - The
@Idannotation specifies the primary key of the entity. - The
@GeneratedValue(strategy = GenerationType.IDENTITY)annotation specifies that the primary key is auto-incremented.
Step 3: Create the Hibernate Utility Class
Create a utility class HibernateUtil to manage the Hibernate SessionFactory. This class ensures a single instance of SessionFactory is created and provides a method to close it.
package com.example.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } } Explanation:
- The
buildSessionFactorymethod creates theSessionFactoryfrom thehibernate.cfg.xmlconfiguration file. - The
getSessionFactorymethod returns the singleton instance ofSessionFactory. - The
shutdownmethod closes theSessionFactoryto release resources.
Step 4: Implement Transaction Management
Create a class UserService to handle database operations with transaction management. This class includes methods to create, read, update, and delete users within transactions.
Create a User
package com.example.service; import com.example.entity.User; import com.example.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; public class UserService { public void createUser(String name, String email) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); User user = new User(); user.setName(name); user.setEmail(email); session.save(user); transaction.commit(); // Commit the transaction } catch (Exception e) { if (transaction != null) { transaction.rollback(); System.out.println("Transaction rolled back due to: " + e.getMessage()); } e.printStackTrace(); } finally { session.close(); } } // Additional methods for reading, updating, and deleting users can be added here. } Explanation:
- The
createUsermethod opens a Hibernate session and begins a transaction. - A new
Userobject is created and saved to the database. - The transaction is committed using
transaction.commit(), ensuring the changes are saved in the database. - If an exception occurs, the transaction is rolled back using
transaction.rollback(). - The session is closed in the
finallyblock to release resources.
Step 5: Demonstrate Transaction Management
Create a MainApp class to demonstrate the transaction management functionality. This class calls the createUser method of UserService to perform database operations within transactions.
package com.example.main; import com.example.service.UserService; public class MainApp { public static void main(String[] args) { UserService userService = new UserService(); // Create a user with valid data userService.createUser("Ramesh Fadatare", "ramesh.fadatare@example.com"); System.out.println("User created with valid data!"); // Create another user with valid data userService.createUser("John Doe", "john.doe@example.com"); System.out.println("Another user created with valid data!"); } } Explanation:
-
Create a
UserServiceInstance:UserService userService = new UserService();An instance of
UserServiceis created to call its methods for performing database operations. -
Create a User with Valid Data:
userService.createUser("Ramesh Fadatare", "ramesh.fadatare@example.com"); System.out.println("User created with valid data!");The
createUsermethod
is called with valid data. This will add a new user to the database and commit the transaction. A message is printed to indicate that the user has been created with valid data.
-
Create Another User with Valid Data:
userService.createUser("John Doe", "john.doe@example.com"); System.out.println("Another user created with valid data!");The
createUsermethod is called again with different valid data. This will add another new user to the database and commit the transaction. A message is printed to indicate that another user has been created with valid data.
Sample Output
When you run the MainApp class, you should see the following output:
User created with valid data! Another user created with valid data! This output indicates that both users were successfully created and their transactions were committed, ensuring the changes were saved in the database.
Conclusion
In this tutorial, we have successfully demonstrated how to manage transactions using session.beginTransaction in Hibernate. We set up a Hibernate project, created an entity class, and implemented transaction management with commit functionality. This guide provides a solid foundation for managing transactions and ensuring data integrity in your Hibernate-based applications.
Comments
Post a Comment
Leave Comment