Hibernate Fundamentals
First Hibernate Example
Build a small Hibernate application that maps an Employee object to a database table and persists it in a transaction.
Steps to Create a Hibernate Application
- Create a persistent entity class.
- Create a mapping configuration.
- Configure the database connection.
- Build a
SessionFactoryand open aSession. - Store or retrieve the persistent object inside a transaction.
- Add Hibernate and database-driver dependencies.
- Run the application from an IDE, Maven, or the command line.
Example Project Structure
hibernate-demo/ pom.xml src/main/java/com/example/Employee.java src/main/java/com/example/StoreData.java src/main/resources/hibernate.cfg.xml
This example uses Hibernate's native bootstrapping API and annotations. Annotations are the recommended starting point for new applications; XML mapping is included below for compatibility with older projects.
1. Create the Persistent Class
A persistent class represents a row in a database table. It should have a no-argument constructor, an identifier, and accessible properties. Keep the class non-final when Hibernate proxies are needed.
package com.example;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
protected Employee() {
// Required by Hibernate.
}
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() { return id; }
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
}- The
@Entityannotation makes the class persistent. @Ididentifies the primary-key property.@GeneratedValuelets the database generate the identifier.- The protected no-argument constructor is available to Hibernate without being part of the public API.
2. Configure Hibernate
Create hibernate.cfg.xml in src/main/resources. Replace the URL, username, password, dialect, and driver with values for your database.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/company</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">change-me</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="com.example.Employee"/>
</session-factory>
</hibernate-configuration>update setting is convenient for learning but should not be relied on for controlled schema changes.3. Add the Required JAR Files
Maven resolves Hibernate's transitive dependencies automatically. Add Hibernate ORM and the JDBC driver to pom.xml:
<dependency> <groupId>org.hibernate.orm</groupId> <artifactId>hibernate-core</artifactId> <version>6.6.9.Final</version> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>9.2.0</version> </dependency>
For a manual setup, the Hibernate core JAR, its transitive dependencies, and the matching database JDBC driver must all be on the classpath. Maven or Gradle is safer because it keeps these versions consistent.
4. Store the Persistent Object
Create a session, begin a transaction, persist the employee, and commit the transaction. Always close the session factory when the application shuts down.
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class StoreData {
public static void main(String[] args) {
try (SessionFactory factory = new Configuration()
.configure()
.buildSessionFactory();
Session session = factory.openSession()) {
Transaction transaction = session.beginTransaction();
try {
session.persist(new Employee("Raj", "Kumar"));
transaction.commit();
System.out.println("Employee saved successfully");
} catch (RuntimeException exception) {
transaction.rollback();
throw exception;
}
}
}
}Optional XML Mapping
Older Hibernate applications may use an Employee.hbm.xml mapping file instead of annotations. The root hibernate-mapping element contains a class mapping, an id mapping, a generator, and property mappings.
<hibernate-mapping>
<class name="com.example.Employee" table="employee">
<id name="id" column="id">
<generator class="identity"/>
</id>
<property name="firstName" column="first_name"/>
<property name="lastName" column="last_name"/>
</class>
</hibernate-mapping>When using XML mapping, register it with <mapping resource="Employee.hbm.xml"/> and remove the annotation-based mapping or choose one mapping strategy deliberately.
5. Run the Application
Ensure that the database exists and the credentials in hibernate.cfg.xml are correct. Then run the class from the project directory:
mvn compile mvn exec:java -Dexec.mainClass="com.example.StoreData"
With a manually assembled classpath, include target/classes, Hibernate dependencies, and the JDBC driver. The exact command depends on the operating system and the location of each JAR, which is why Maven or Gradle is recommended.
What Happens Internally?
Configurationreads the Hibernate configuration and entity mappings.SessionFactoryis built from that metadata and is normally reused.- A
Sessionopens a persistence context and a transaction starts. persist()makes the new entity managed.- On commit, Hibernate flushes an
INSERTstatement through JDBC. - The session and factory close, releasing resources.
employee table, and Hibernate prints the generated SQL when hibernate.show_sql is enabled.Common Problems Checklist
- Check that the database server is running and the schema exists.
- Verify the JDBC driver, URL, username, and password.
- Use
jakarta.persistenceimports with Hibernate 6; older Hibernate 5 projects may usejavax.persistence. - Confirm that the entity class is registered by annotation scanning or mapping configuration.
- Rollback a failed transaction before closing the session.
- Do not create a new
SessionFactoryfor every database operation.
