Saturday 20 January 2018

What are the Core Interfaces of Hibernate framework ?

               Hibernate is an Open source Object Relational Mapping(ORM) framework. It enables developer to develop classes to be persist in an object oriented way including inheritance and the Java collections framework. It can provide high performance because of caching algorithm,  check the advantages of Hiberante over Jdbc  in previous post.
           
             Hibernate can provides different interfaces and classes, but I have listed core interfaces as below,

  • Session interface
  • SessionFactory interface
  • Configuration interface
  • Transaction interface
  • Query and Criteria interfaces


Session interface

        It is a single threaded, short-lived object representing a conversation between the application and the persistent store.

It allows you to create query objects to retrieve persistent objects. It's not thread safe.

Synatx:-

Session session = sessionFactory.openSession();

Example:-


  Session session = factory.openSession();
  Transaction tx = null;

  try {
      tx = session.beginTransaction();
      // do some work
      .....
      tx.commit();
  }

  catch (Exception e) {
      if (tx!=null) tx.rollback();
      e.printStackTrace(); 
  } finally {
      session.close();
  }


SessionFactory interface

        The application obtains session instances from SessionFactory. 
There is typically a single SessionFactory for the whole application created 
during application loading.

Syntax:-
SessionFactory sessionFactory = configuration.buildSessionFactory();

Example:-


package com.adnblog;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
 
    public static SessionFactory factory;
 
    private HibernateUtil() {
    }
   
     //making the Hibernate SessionFactory object as singleton
 
    public static synchronized SessionFactory getSessionFactory() {
 
        if (factory == null) {
            factory = new Configuration().configure("hibernate.cfg.xml").
                    buildSessionFactory();
        }
        return factory;
    }
}



Configuration interface

            This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify  the location of hibernate specific mapping documents.

Syntax:--


Configuration configuration = new Configuration();

configuration.configure();



Transaction interface

               This interface abstracts the code from any kind of transaction implementation such as JDBC transaction, JTA Transanction.

Syntax:--


session.beginTransaction();

session.save(user);

session.update(user_payrole);

session.getTransaction().commit();


Query and Criteria interfaces

           This interface allows the user to perform queries and also control the flow of the query execution.

Syntax:--

No comments:

Post a Comment