Step 3- Hibernate Mapping Files Setup

Important –

Table – Java : Hibernate : sql datatypes mapping

comparison of the data types for Java, Hibernate, and SQL:

Java Data TypeHibernate Data TypeSQL Data Type

Now we have following two steps to use all the configuration which we have performed-

Step 1- Defining Mapping files – (Java class to tables conversion)
Step 2- Creating Session factory, session and transaction objects to perform DB operations.

Step 1– Once the configuration file is set up from previous Topic-

  • After setting up the configuration file, define mapping files
  • These files map persistent objects in the application to database tables
  • Mapping files can be in XML or annotations format
  • They specify the correspondence between fields in persistent objects and columns in database tables.

Here is an example of a basic mapping file, mypersistentobject.hbm.xml, for a class called MyPersistentObject:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    <class name="com.mypackage.MyPersistentObject" table="my_persistent_object">
        <id name="id" column="id" type="long">
            <generator class="increment"/>
        <property name="name" column="name" type="string"/>
        <property name="description" column="description" type="string"/>

and below is related MyPersistentObject class-

public class MyPersistentObject {

private long id;

private String name;

private String description;

// getters and setters


Note – Other ways to create same mapping file,

1- Using annotations: Instead of creating a separate mapping file, the mapping information can be added directly to the entity class using annotations, such as @Entity, @Table, @Id, @Column, etc.

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Column;

@Table(name = "my_persistent_object")
public class MyPersistentObject {

    @Column(name = "id")
    private long id;

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

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

    // getters and setters

2- Using JPA XML Meta-data: JPA also allows you to use an xml file instead of annotations to map the entities.

<entity-mappings xmlns=""
    <entity class="com.mypackage.MyPersistentObject" access="FIELD">
        <table name="my_persistent_object" />
            <id name="id" >
                <generated-value strategy="IDENTITY" />
            <basic name="name" >
                <column name="name" nullable="false" unique="true" />
            <basic name="description" >
                <column name="description"  />

3- Using programmatic configuration: Instead of using an XML file, you can use a programmatic configuration to map the entities by simply creating an instance of org.hibernate.mapping.PersistentClass and set its properties accordingly.

import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.Column;

public class MappingHelper {
    public static void addMapping(Configuration configuration) {
        PersistentClass persistentClass = new PersistentClass(MyPersistentObject.class, configuration.createMappings());
        SimpleValue id = new SimpleValue(configuration.createMappings());
        id.addColumn(new Column(configuration.getIdentifierColumnName()));
        Property name = persistentClass.createProperty("name", new SimpleValue(configuration.createMappings()), "string");
name.setColumn(new Column("name"));
Property description = persistentClass.createProperty("description", new SimpleValue(configuration.createMappings()), "string");
description.setColumn(new Column("description"));

Step 2- Finally,

  • Set up Hibernate session factory
  • The session factory is responsible for creating and managing sessions
  • A session is used to interact with the database
  • Through the session factory, you can create, retrieve, and delete persistent objects.

Here is an example of how to set up the Hibernate session factory:

// Create the Configuration
Configuration configuration = new Configuration().configure();

// Create the ServiceRegistry
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()

// Create the SessionFactory
SessionFactory sessionFactory = configuration

Note – Alternative ways to create sessionFactory object –

One alternative way to create the SessionFactory is to use the static method buildSessionFactory() on the Configuration class, like this:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

Another alternative is to use the SessionFactoryBuilder class, like this:

SessionFactoryBuilder builder = new SessionFactoryBuilder(new StandardServiceRegistryBuilder().configure());
SessionFactory sessionFactory =;

Note that the configure() method can take the path of the configuration file as an argument and it will load the configuration from that file instead of the default hibernate.cfg.xml file.

SessionFactory sessionFactory = new Configuration().configure("/path/to/config/file").buildSessionFactory();


SessionFactoryBuilder builder = new SessionFactoryBuilder(new StandardServiceRegistryBuilder().configure("/path/to/config/file"));
SessionFactory sessionFactory =;

Step 5 –

  • Once all the steps are completed, use the session factory to create a session
  • Use the session to interact with the database
  • For example, create a new instance of a persistent object and save it to the database using the session.
// Open a new session
Session session = sessionFactory.openSession();

// Begin a transaction

// Create a new instance of MyPersistentObject
MyPersistentObject myObject = new MyPersistentObject();
myObject.setName("My Object");
myObject.setDescription("This is my persistent object");

// Save the object to the database;

// Commit the transaction

// Close the session

Note – Alternatively we can use more modern ways to write above codes –

try (Session session = sessionFactory.openSession()) {

    MyPersistentObject myObject = new MyPersistentObject();
    myObject.setName("My Object");
    myObject.setDescription("This is my persistent object");;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.