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
booleanbooleanBOOLEAN
bytebyteTINYINT
charcharacterCHAR
shortshortSMALLINT
intintegerINT
longlongBIGINT
floatfloatFLOAT
doubledoubleDOUBLE
StringstringVARCHAR
DatedateDATE
TimestamptimestampTIMESTAMP
BigDecimalbig_decimalDECIMAL

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"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.mypackage.MyPersistentObject" table="my_persistent_object">
        <id name="id" column="id" type="long">
            <generator class="increment"/>
        </id>
        <property name="name" column="name" type="string"/>
        <property name="description" column="description" type="string"/>
    </class>
</hibernate-mapping>

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;

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

    @Id
    @GeneratedValue
    @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="http://java.sun.com/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
    http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
    version="2.0">
    <entity class="com.mypackage.MyPersistentObject" access="FIELD">
        <table name="my_persistent_object" />
        <attributes>
            <id name="id" >
                <generated-value strategy="IDENTITY" />
            </id>
            <basic name="name" >
                <column name="name" nullable="false" unique="true" />
            </basic>
            <basic name="description" >
                <column name="description"  />
            </basic>
        </attributes>
    </entity>
</entity-mappings>

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());
        persistentClass.setTable(configuration.getTable("my_persistent_object"));
        SimpleValue id = new SimpleValue(configuration.createMappings());
        id.setIdentifierGeneratorStrategy("increment");
        id.setTypeName("long");
        id.addColumn(new Column(configuration.getIdentifierColumnName()));
        persistentClass.setIdentifier(id);
        Property name = persistentClass.createProperty("name", new SimpleValue(configuration.createMappings()), "string");
name.setColumn(new Column("name"));
persistentClass.addProperty(name);
Property description = persistentClass.createProperty("description", new SimpleValue(configuration.createMappings()), "string");
description.setColumn(new Column("description"));
persistentClass.addProperty(description);
configuration.addClass(persistentClass);
}
}

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()
.applySettings(configuration.getProperties())
.build();

// Create the SessionFactory
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);

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 = builder.build();

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();

or

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

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
session.beginTransaction();

// 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
session.save(myObject);

// Commit the transaction
session.getTransaction().commit();

// Close the session
session.close();

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

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

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

    session.save(myObject);

    session.getTransaction().commit();
}
Advertisement

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.