What is Session object in Hibernate?
Unlike SessionFactory, the Session object will be created on demand. Session is a lightweight object. Session
provides a physical connectivity between your application and database. The Session will be established each time your application
wants do something with database. Session object will be provided by SessionFactory object. All the persistent objects will be
saved and retrieved through Session object. The session object must be destroyed after using it.
The lifecycle of a Session is bounded by the beginning and end of a logical transaction. The main function of
the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one
of three states:
- transient: never persistent, not associated with any Session.
- persistent: associated with a unique Session.
- detached: previously persistent, not associated with any Session.
Here is the sample implementation for getting Session object from SessionFactory:
HibernateUtil |
package com.java2novice.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.java2novice.model.Employee;
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
static {
try{
loadSessionFactory();
}catch(Exception e){
System.err.println("Exception while initializing hibernate util.. ");
e.printStackTrace();
}
}
public static void loadSessionFactory(){
Configuration configuration = new Configuration();
configuration.configure("/j2n-hibernate.cfg.xml");
configuration.addAnnotatedClass(Employee.class);
ServiceRegistry srvcReg = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(srvcReg);
}
public static Session getSession() throws HibernateException {
Session retSession=null;
try {
retSession = sessionFactory.openSession();
}catch(Throwable t){
System.err.println("Exception while getting session.. ");
t.printStackTrace();
}
if(retSession == null) {
System.err.println("session is discovered null");
}
return retSession;
}
}
|
|