hibernate之openSession和getCurrentSession

本文深入探讨了Hibernate中session的两种创建方式:openSession和getCurrentSession的区别,包括它们的工作原理、自动关闭机制以及如何正确使用以避免资源泄露。同时,文章还分析了Spring和Hibernate集成时的初始化过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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进行初始化进行详细分析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值