Set up a Hibernate database connection in Java with XML Configuration - step by step

To set up a Hibernate database connection in Java, you will need to configure Hibernate in a Java application and establish a connection to a database. Here's how you can do it step by step:

1. Add Hibernate Dependencies

If you're using Maven, add the following dependencies in your pom.xml file:

<dependencies>
<!-- Hibernate core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.10.Final</version> <!-- Use the latest stable version -->
</dependency>

<!-- Hibernate Validator (Optional, for validation) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>

<!-- JDBC Driver for your database -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version> <!-- For MySQL -->
</dependency>
</dependencies>

If you're using Gradle, add the following:

dependencies {
    implementation 'org.hibernate:hibernate-core:5.6.10.Final'
    implementation 'org.hibernate:hibernate-validator:6.0.13.Final'
    implementation 'com.mysql:mysql-connector-j:8.3.0'  // For MySQL
}


2. Configure hibernate.cfg.xml

Create a Hibernate configuration file named hibernate.cfg.xml inside the src/main/resources directory of your project. Here's an example configuration for connecting to a MySQL database:

<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.driver_class">
com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.url">
jdbc:mysql://localhost:3306/your_database</property>
<property name="hibernate.username">
your_username</property>
<property name="hibernate.password">
your_password</property>

<!-- JDBC connection pool settings -->
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>

<!-- Specify the JDBC transaction management -->
<property name="hibernate.transaction.coordinator_class">
org.hibernate.transaction.JDBCTransactionFactory</property>

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

<!-- Drop and re-create the database schema on startup -->
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="hibernate.current_session_context_class">
thread</property>

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

</session-factory>
</hibernate-configuration>


3. Create an Entity Class

Next, create an entity class that represents a table in the database. This class should be annotated with Hibernate annotations.

Example:

import javax.persistence.*;

@Entity
@Table(name = "employee")
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "email")
private String email;

// Getters and Setters
}


4. Create a Hibernate Utility Class

You can create a utility class to manage the session factory and Hibernate sessions.

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

public class HibernateUtil {

private static SessionFactory factory;

static {
try {
factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(Employee.class)
.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}

public static Session getSession() {
return factory.getCurrentSession();
}

public static void closeSession() {
if (factory != null) {
factory.close();
}
}
}


5. Create a Main Class to Test the Connection

Now you can write a simple test to insert a record into the database.

import org.hibernate.Session;

public class MainApp {

public static void main(String[] args) {
// Create a new employee object
Employee newEmployee = new Employee();
newEmployee.setFirstName("John");
newEmployee.setLastName("Doe");
newEmployee.setEmail("john.doe@example.com");

// Get the session from HibernateUtil
Session session = HibernateUtil.getSession();

try {
// Start a transaction
session.beginTransaction();

// Save the employee object
session.save(newEmployee);

// Commit the transaction
session.getTransaction().commit();
} finally {
// Close the session
session.close();
}

HibernateUtil.closeSession();
}
}


6. Run the Application

After you've completed the above steps, run the MainApp class. If everything is set up correctly, Hibernate will connect to your MySQL database, insert the employee record, and handle transactions automatically.


Common Issues to Check

  • Database Connection: Ensure that your database is running and accessible from the application.
  • JDBC Driver: Make sure you're using the correct JDBC driver for your database.
  • Hibernate Dialect: Ensure that you're using the correct Hibernate dialect for your database (e.g., MySQLDialect for MySQL).

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete