1

I'm using Hibernate withhout @annotations

I tried this code:

    public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    private static StandardServiceRegistryBuilder builder;

    static {
        try {
            Configuration configuration = new Configuration().configure();
            configuration.configure("hibernate.cfg.xml");
            builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
            sessionFactory = configuration.buildSessionFactory(builder.build());
        } catch (HibernateException ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Client code:

    public static void main (String[] args) {                                         
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    Criteria criteria = session.createCriteria(Customer.class);
    List<Customer> customers = criteria.list();
    for (Customer customer : customers) {
        //print values
    }
    session.getTransaction().commit();
    session.close();
}

Also here is important thing I want to know
What if I will create HibernateUtil class object in Client class?

HibernateUtil hibernateUtil = new HibernateUtil();
Swapnil
  • 115
  • 1
  • 12

2 Answers2

0

You can refer stackoverflow link: What are the advantages and disadvantages of creating an Object in static block in Java?.

If you want SessionFactory to be created when your server or application starts, then static block can be used. else, go for static method approach. You can also use enums to create singleton.

Vipul
  • 545
  • 1
  • 8
  • 30
  • 1
    When you use a static block, it means before creating an instance to HibernateUtil static block will be executed, meaning your SessionFactory in HibernateUtil is created and available for service through getSessionFactory() static method. This is early instantiation of object. In this case, you do not have to create an object for HibernateUtil. directly invoke static method on HibernateUtil class and get the instance for SessionFactory. – Vipul Sep 16 '19 at 16:22
  • I used this `public class SingltoneHiber extends javax.swing.JFrame { private SessionFactory sessionFactory; public SingltoneHiber() { this.sessionFactory = HibernateUtil.getSessionFactory(); initComponents(); }` – Swapnil Sep 17 '19 at 08:53
0

So, you've got two questions there, one about this being the right approach to create a singleton, and the other about what happens if you create a HibernateUtil instance in the client.

First for the HibernateUtil

For the second question, you're fine if each client creates an instance of the HibernateUtil class, as the variable is static. If all goes according to plan, there will only be one Hibernate SessionFactory instance.

As for whether you have a correct Hibernate SessionFactory singleton implementation? That's a harder question to answer. While your code looks good, multiple classloaders can cause all sorts of unpredictable problems with singletons. If separate classloaders create an instance, you may have multiple instances of your singleton, a paradox you want to avoid.

EJB and Spring Singleton help

With the EJB specification, you can mark a session bean as a singleton. If you are using a Java web profile compliant server, I'd do that. If you are using Spring Boot, use the singleton facilities they provide. If it's a standalone application, keep an eye out for peculiar, non-singleton SessionFactory behavior.

Cameron McKenzie
  • 3,684
  • 32
  • 28