0

I found a the HibernateUtil class in my Package, it contains an unknown syntax for me. I don't know what it is and how this works:

public class HibernateUtil {
private static final SessionFactory sessionFactory;
//???
static {
    try{
        //Create the SessionFactory from standard config file (hibernate.cfg.xml)
        Configuration configuration = new Configuration().configure();
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());

        sessionFactory = configuration.buildSessionFactory(builder.build());
    }catch (Throwable ex){
        //Log the Exception
        System.err.println("Initial SessionFactory creation failed: "+ ex);
        throw new ExceptionInInitializerError(ex);
    }
 }

 public static SessionFactory getSessionFactory() {
    return sessionFactory;
 }
}
Nirmal
  • 1,229
  • 1
  • 15
  • 31
Zion
  • 723
  • 3
  • 7
  • 24
  • So what is ur question ? – OO7 Apr 10 '15 at 12:25
  • That's vague. We can't start explaining ALL of that code. Try to ask one or more specific questions. – Manu Apr 10 '15 at 12:27
  • This class searches for `hibernate.cfg.xml` file in the classpath & once found it establishes a connection between database specified in config file & ur application. So that ur application have an access to DB & can perform CRUD operation in DB. – OO7 Apr 10 '15 at 12:27
  • the call ´static{ }´ what is this? is java 8 or auto completion ? – Zion Apr 10 '15 at 12:29
  • This is static block in Java, it means no need to create an object of this class to create sessionFactory. The static code always executed first. U should learn basics of Java. We are not here to teach u from basic. – OO7 Apr 10 '15 at 12:31
  • thanks static block was the keyword [static block](http://stackoverflow.com/questions/2943556/static-block-in-java) – Zion Apr 10 '15 at 12:33

2 Answers2

0

As it says, it is an utility class with a static block. This class make sure to have a session ready for your program. You would use this to get a handle on the session to work with your database.

A static block makes sure that it is run as the class loader loads the class into JVM. Here is more on JLS Static Block

Nirmal
  • 1,229
  • 1
  • 15
  • 31
0

This is Hibernate SessionFactory singleton class. It create the SessionFactory object at the Class loading time. it read database properties from your Hibernate.cfg.xml file which is present in your src folder.

Whenever you want a SessionFactory object just call its instance method as shown below :

HibernateUtil.getSessionFactory();

kavi temre
  • 1,321
  • 2
  • 14
  • 21