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) {
        this.id = id;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(id).append(":").append(message);
        return sb.toString();
    }
}

Below is the mapping file

Message.hbm.xml


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

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

Below is the hibernate configuration file

hibernate.cfg.xml


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <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="hibernate.hbm2ddl.auto">create</property>
    <property name="hibernate.show_sql">true</property>
    
    <mapping resource="Message.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

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

HibernateUtil


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) {
                e.printStackTrace();
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(registry);
                }
            }
        }
        return sessionFactory;
    }
    
    public static void shutdown() {
        if (registry != null) {
            sessionFactory.close();
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }
}

Below is the complete main code

Main Code


1  import org.hibernate.Session;
2  import org.hibernate.SessionFactory;
3  
4  public class HibernateDemo1 {
5   public static void main(String[] args) {
6       SessionFactory sessionFactory = HibernateUtil.createSessionFactory();
7          Session session = sessionFactory.openSession();
8          
9          Message message = new Message();
10         message.setMessage("Hello World");
11         
12         session.beginTransaction();
13         session.save(message);
14         session.getTransaction().commit();
15         
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

Advertisements

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 )

Google photo

You are commenting using your Google 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