Hibernate session close

In this section, you will learn about session life cycle - from start to end(session close).

Hibernate session close

Hibernate session close

In this section, you will learn about session life cycle - from start to end(session close).

The Life cycle of Session starts with starting and ending of  transaction. The transaction might have various transaction of different database.

The Session offers insert, read and delete operations on database table using mapped entity classes.

An entity class object exists in three states :

  • transient : An entity class instance is said to be in transient state when it is not associated with any Session.

  • persistent : An entity class instance is said to be  persistent when it is associated with Session.

  • detached : The entity class instance which is previously persistent but right now it is not associated with any Session.

Transient instances can be converted into persistent by calling save(), persist() or saveOrUpdate() method.

A Session instance is serializable if its persistent classes are serializable.

You can create and use Session instance as follows :

package net.roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class ManageEmployee {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

@SuppressWarnings("unchecked")
public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("Hibernate One to Many Mapping Example Using Annotation ");
Session session = sf.openSession();
session.beginTransaction();

Address address = new Address();
address.setStreet("Lake Gardens");
address.setCity("Kolkata");
address.setState("West Bengal");
address.setCountry("India");
session.save(address);

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