Create a Hibernate Application with Java-Based Configuration (No XML)

Ramesh Fadatare
4 min readJan 24, 2025

--

In this guide, we will create a simple Hibernate application using Java-based configuration without XML. We will use Hibernate 6, MySQL, and Maven as the build tool. The project will run on Eclipse IDE. This tutorial walks you through step-by-step, including writing code and explanations for each part.

Hibernate is a popular Object-Relational Mapping (ORM) framework for Java. It simplifies database operations by mapping Java objects to relational database tables.

Development Steps

  1. Create a Simple Maven Project
  2. Project Directory Structure
  3. Add Dependencies to pom.xml
  4. Create a JPA Entity Class
  5. Configure Hibernate Java-Based Settings
  6. Create a DAO Class
  7. Run the Application

1. Create a Simple Maven Project

Use the Eclipse IDE to create a Maven project. Follow the How to Create a Simple Maven Project article if you’re unfamiliar.

2. Project Directory Structure

The project directory structure for your reference:

3. Add Dependencies to pom.xml

Add the following dependencies for Hibernate 6 and MySQL to the pom.xml file:

Explanation:

  • MySQL Connector: Provides the JDBC driver to connect to the MySQL database.
  • Hibernate Core: The main Hibernate library that enables ORM features.
  • Jakarta Persistence API: Replaces the older javax.persistence API.
<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>net.javaguides</groupId>
<artifactId>hibernate-java-config-example</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<!-- MySQL Connector -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>

<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.2.6.Final</version>
</dependency>

<!-- Jakarta Persistence API -->
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
</project>

4. Create a JPA Entity Class

This class represents the database table. Hibernate maps this class to a relational table.

  • @Entity: Marks the class as a JPA entity.
  • @Table: Specifies the table name in the database.
  • @Id: Marks the field as the primary key.
  • @GeneratedValue: Specifies the primary key generation strategy (e.g., auto-increment).
  • @Column: Maps fields to specific database columns.
package net.javaguides.hibernate.model;  

import jakarta.persistence.*;

@Entity
@Table(name = "student") // Table name in the database
public class Student {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // Auto-incremented ID
private int id;

@Column(name = "first_name", nullable = false) // Maps firstName to first_name column
private String firstName;

@Column(name = "last_name", nullable = false) // Maps lastName to last_name column
private String lastName;

@Column(name = "email", unique = true, nullable = false) // Email is unique and mandatory
private String email;

// Default constructor (required by Hibernate)
public Student() {}

// Parameterized constructor
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

// Getters and setters for accessing private fields
public int getId() { return id; }
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String getEmail() { return email; }
}

5. Configure Hibernate Java-Based Settings

Create the HibernateUtil class to configure Hibernate properties programmatically. This eliminates the need for hibernate.cfg.xml.

  • StandardServiceRegistryBuilder: Configures Hibernate using the provided settings.
  • addAnnotatedClass: Registers entity classes with Hibernate.
  • Hibernate Properties:
  • hibernate.connection.url: Database connection URL.
  • hibernate.dialect: Specifies the SQL dialect for MySQL.
  • hibernate.hbm2ddl.auto: Defines schema generation strategy (e.g., update, create-drop).
package net.javaguides.hibernate.util;

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import net.javaguides.hibernate.model.Student;

public class HibernateUtil {
private static SessionFactory sessionFactory;

public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();

// Hibernate settings
Properties settings = new Properties();
settings.put("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
settings.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate_demo?useSSL=false");
settings.put("hibernate.connection.username", "root");
settings.put("hibernate.connection.password", "password");
settings.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
settings.put("hibernate.show_sql", "true");
settings.put("hibernate.hbm2ddl.auto", "update");

configuration.setProperties(settings);
configuration.addAnnotatedClass(Student.class);

StandardServiceRegistryBuilder serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());

sessionFactory = configuration.buildSessionFactory(serviceRegistry.build());
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}

6. Create a DAO Class

The StudentDao class handles database operations.

  • Session: Represents the database connection and performs operations like saving objects.
  • Transaction: Manages transaction boundaries.
  • try-with-resources: Automatically closes the session.
package net.javaguides.hibernate.dao;

import org.hibernate.Session;
import org.hibernate.Transaction;

import net.javaguides.hibernate.model.Student;
import net.javaguides.hibernate.util.HibernateUtil;

public class StudentDao {
public void saveStudent(Student student) {
Transaction transaction = null;

try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
session.persist(student); // Save the student entity
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback(); // Rollback if any error occurs
}
e.printStackTrace();
}
}
}

7. Run the Application

Finally, test the application by saving a student record to the database.

  • Create a Student object: Pass values to the constructor.
  • Call saveStudent: Persists the object to the database.
  • Output: Prints the auto-generated ID after saving.
package net.javaguides.hibernate;

import net.javaguides.hibernate.dao.StudentDao;
import net.javaguides.hibernate.model.Student;

public class App {
public static void main(String[] args) {
StudentDao studentDao = new StudentDao();
Student student = new Student("Rajesh", "Sharma", "rajesh.sharma@gmail.com");
studentDao.saveStudent(student);
System.out.println("Student saved successfully!");
}
}

Output:

Conclusion

This tutorial demonstrated how to set up a simple Hibernate application using Java-based configuration with Hibernate 6. Key topics included Maven setup, jakarta API, Hibernate settings, and saving entities to a MySQL database.

For more Hibernate tutorials, visit JavaGuides.

--

--

No responses yet