Hibernate中的Singleton SessionFactory

时间:2016-03-24 14:39:06

标签: java hibernate singleton sessionfactory

我最近开始使用Hibernate,但这个问题令我感到困惑。我已经看到,如果我们有多个数据源,可以多次创建Session Factory。但同时我也读到sessionFactory也实现了singleton。这不矛盾??

1 个答案:

答案 0 :(得分:-1)

//use singleton hibernateUtil.java class
package com.onlinetutorialspoint.config;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtility {
public static SessionFactory factory;
//to disallow creating objects by other classes.

    private HibernateUtility() {
    }
//maling the Hibernate SessionFactory object as singleton

    public static synchronized SessionFactory getSessionFactory() {

        if (factory == null) {
            factory = new Configuration().configure("hibernate.cfg.xml").
                    buildSessionFactory();
        }
        return factory;
    }
}