SessionFactory得到Session的方法有两种getCurrentSession和openSession两种
更据Hibernate文档说明,在Hibernate3.2之后不再建议使用openSession,推荐使用getCurrentSession方法来获得Session对象。分别来说下两种获得Session的区别:
openSession:
表示创建一个
Session
,使用后需要关闭这个
Session
getCurrentSession:
表示当前环境没有
Session
时,则创建一个,否则不用创建
两方法的区别:
①、
openSession
永远是每次都打开一个新的
Session,
而
getCurrentSession
不是,是从
上下文
找、只有当前没有
Session
时,才创建一个新的
Session
②、
OpenSession
需要手动
close,getCurrentSession
不需要手动
close
,事务提交自动
close
③、
getCurrentSession
界定事务边界
上下文:
所指的上下文是指
hibernate
配置文件
(hibernate.cfg.xml)
中的“
current_session_context_class
”所指的值:
(
可取值:
jta|thread|managed|custom.Class)
< property name = "current_session_context_class" > thread </ property
常用的是:
①、
thread
:
是从
上下文
找、只有当前没有
Session
时,才创建一个新的
Session
,主要从数据界定事务
②、
jta
:主要从分布式界定事务,运行时需要
Application Server
来支持
(Tomcat
不支持
)
小概念:
(
jta
:
Java Transaction
API
)
(
jpa
:
Java
Persistence API
)
③、
managed:
不常用
④、
custom.Class:
不常用
两方法的写法:
openSession:
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(student);
session.getTransaction().commit();
session.close();
getCurrentSession:
SessionFactory sf = new Configuration().configure().buildSessionFactory();
//拿到当前session ,若是没有则创建一个session,若存在则拿当前的session
Session session = sf.getCurrentSession();
session.beginTransaction();
session.save(student);
session.getTransaction().commit();
分享到:
相关推荐
【hibernate学习笔记】 在Java开发中,Hibernate是一个强大的对象关系映射(ORM)框架,它极大地简化了数据库操作。以下是对Hibernate的学习要点的详细解释: 1. **建立第一个Hibernate版本的HelloWorld** - **...
hibernate 学习笔记: 了解hibernate的基本概念 配置hbm.xml cfg.xml 快速入门案例3: 从domain-xml-数据库表 hibernate的核心类和接口 openSession()和getCurrentSession() 线程局部变量模式 transaction事务 在web...
本文主要围绕Hibernate 3.2的学习笔记,涵盖其基本概念、配置、映射机制以及核心开发接口。 一、O/R Mapping简介与优点 1. O/R Mapping(对象关系映射)是为了解决面向对象编程与关系型数据库之间的差异,通过在...
在这四天的学习笔记中,我们将深入探讨Hibernate的核心概念、配置、实体管理以及查询语言,帮助你全面掌握这个流行的持久层框架。 一、Hibernate 概述 Hibernate 提供了一种映射机制,将Java类与数据库表进行对应,...
在Hibernate中,我们有两种方式来获取和管理Session:`openSession()`和`getCurrentSession()`。`openSession()`每次都会创建一个新的Session,并且在使用完毕后需要手动关闭,这适用于短生命周期的事务。而`...