Saving a transient object

In this post of Hibernate ORM, I will explain how to save a transient object with an example.

A transient object exists only in memory, no representation of it exists in database. Hibernate runtime doesn’t manage (ie., automatically update or sync up with database representation) the transient object. The object’s identifier property value will be null.

To save a transient object we need to first create a mapping file. The mapping file will show how the fields in the class and the class itself are mapped to columns and table in the database. Below is the Message class

Message class

public class Message {
    private int id;
    private String message;
    public int getId() {
        return id;
    public void setId(int id) { = id;
    public String getMessage() {
        return message;
    public void setMessage(String message) {
        this.message = message;
    public String toString() {
        StringBuilder sb = new StringBuilder();
        return sb.toString();

Below is the mapping file


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    <class name="Message" table="Message">
        <id type="int" name="id" column="id">
            <generator class="native"/>
        <property name="message" column="message" type="string"/>

As shown in the mapping file, class Message is mapped to Message table.

Below is the hibernate configuration file


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"

    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/examples</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    <property name="">create</property>
    <property name="hibernate.show_sql">true</property>
    <mapping resource="Message.hbm.xml"/>

We create a utility class named HibernateUtil which reads the above hibernate configuration file and creates an instance of SessionFactory, as shown below


import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;
    public static SessionFactory createSessionFactory() {
        if (sessionFactory == null) {
            try {
                // Create registry
                registry = new StandardServiceRegistryBuilder().configure().build();

                // Create MetadataSources
                MetadataSources sources = new MetadataSources(registry);

                // Create Metadata
                Metadata metadata = sources.getMetadataBuilder().build();

                // Create SessionFactory
                sessionFactory = metadata.getSessionFactoryBuilder().build();
            } catch (Exception e) {
                if (registry != null) {
        return sessionFactory;
    public static void shutdown() {
        if (registry != null) {

Below is the complete main code

Main Code

1  import org.hibernate.Session;
2  import org.hibernate.SessionFactory;
4  public class HibernateDemo1 {
5   public static void main(String[] args) {
6       SessionFactory sessionFactory = HibernateUtil.createSessionFactory();
7          Session session = sessionFactory.openSession();
9          Message message = new Message();
10         message.setMessage("Hello World");
12         session.beginTransaction();
14         session.getTransaction().commit();
16         session.close();
17         HibernateUtil.shutdown();
18  }
19 }

At line 6, we create an instance of SessionFactory.

Using the instance of SessionFactory, we create an instance of Session, refer to line 7.

At line 9 & 10, we create a transient instance of Message class and set it message property to “Hello World”.

At line 12, we start a new transaction by calling session.beginTransaction().

At line 13, we call the save method passing the message instance.

At line 14, we commit the transaction.

Once committed the hibernate creates a database entry in Message table, sets value to the id property of Message object. From now on the Message instance is no longer a transient object, it is a Persistent object.

A Persistent object exists in memory and also in database. Hibernate runtime does manage (ie., automatically update or sync up with database representation) the object. The object’s identifier property value will be not null.

At line 16, we close the session.

At line 17, we close the SessionFactory instance by calling shutdown

Check these products on Amazon

Leave a Reply