hibernate通过sessionFactory有两种方式获取session:一种是openSession,一种是getCurrentSession
简单区别
1、openSession创建session时autoCloseSessionEnabled参数为false,即在事物结束后不会自动关闭session,需要手动关闭,如果不关闭将导致session关联的数据库连接无法释放,最后资源耗尽而使程序当掉。 2、getCurrentSession创建session时autoCloseSessionEnabled,flushBeforeCompletionEnabled都为true,并且session会同sessionFactory组成一个map以sessionFactory为主键绑定到当前线程。
3、现在对hibernate两种创建session方式进行详细描述:
3.1入口:
private static SessionFactory buildSessionFactory() {
try {
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
In Hibernate 3.6, “org.hibernate.cfg.AnnotationConfiguration
” is deprecated, and all its functionality has been moved to “org.hibernate.cfg.Configuration
“.
private static SessionFactory buildSessionFactory() {
try {
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
spring3.0.6和hibernate3.6.7集成: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean进行初始化,里面调用的是new AnnotationConfiguration().configure().buildSessionFactory();
下面的文章将对spring加载配置hibernate进行初始化进行详细分析