孙卫琴的java书中写到hibernate中SessionFactory是单例类,并且网上也有很多文章说是SessionFactroy是单例的。我测试的时候
SessionFactory sf1 = config.buildSessionFactory();
SessionFactory sf2 = config.buildSessionFactory();
System.out.println(sf1==sf2);
为什么输出的是false呢
------解决方案--------------------
看一下源代码便知道了,buildSessionFactory每次都会new一个sessionFactory
- Java code
public SessionFactory buildSessionFactory() throws HibernateException { log.debug( "Preparing to build session factory with filters : " + filterDefinitions ); secondPassCompile(); validate(); Environment.verifyProperties( properties ); Properties copy = new Properties(); copy.putAll( properties ); PropertiesHelper.resolvePlaceHolders( copy ); Settings settings = buildSettings( copy ); return new SessionFactoryImpl( this, mapping, settings, getInitializedEventListeners() ); }
------解决方案--------------------
sessionFactory是重量级的,通常我们在一个单数据源的应用里,只需要一个sessionFactory,所以我们一般采用单例的模式来处理,但是不是说sessionFactory这个类是单例的。这个是我们自己去实现的
比如myeclipse自动生成的HibernateSessionFactory
private static org.hibernate.SessionFactory sessionFactory;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
------解决方案--------------------
这个机制其实很是安全 因为每使用一次就会创建一个新的 sessionFactory
------解决方案--------------------
hibernate sessionFactory每使用一次就会创建一个新的 sessionFactory
------解决方案--------------------
------解决方案--------------------
需要自己实现单例,sessionFactory是重量级对象,而且是线程安全的,所以大部分教程都推荐要将sessionFactory设计成单例的。但是hibernate本身并没有直接设计成单例,因为它还要考虑到同一个程序要访问多个数据库的情况。