Topic 3- Hibernate Mapping Files Setup

image 2

Play Store Application link – Hibernate – in 10 steps – Apps on Google Play

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
1- basic mapping file, mypersistentobject.hbm.xml put it in resources folder with hibernate.cfg.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,

2- 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
}

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

Step 3 –

  • 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, which will handle session closing automatically –

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

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *