Hibernate——SessionFactory产生session的两种方法
来源:互联网 发布:阿里巴巴农村淘宝兰西 编辑:程序博客网 时间:2024/06/05 00:45
SessionFactory可以简单理解为数据库的连接池,用于产生session
产生session有两种方法
(1)Session session = sf.openSession();
(2)Session session = sf.getCurrentSession();
openSession每次都创建一个新的session,需要手动close
getCurrentSession如果没有提交过,一直用同一个session,提交后,新建一个session
(从上下文找,如果有,用旧的,如果没有,建新的)
i.用途,界定事物边界(事物的开始和结束,从beginTransaction到commit transaction)
产生session有两种方法
(1)Session session = sf.openSession();
(2)Session session = sf.getCurrentSession();
openSession每次都创建一个新的session,需要手动close
getCurrentSession如果没有提交过,一直用同一个session,提交后,新建一个session
(从上下文找,如果有,用旧的,如果没有,建新的)
i.用途,界定事物边界(事物的开始和结束,从beginTransaction到commit transaction)
ii.事物提交自动close
假设有一个addUser()方法,要对数据库执行save(User)和addLog()两个操作,这两个操作要放在一个transaction中,要么同时完成,要么都不完成。此时两个session就要是同一个session,不然不能放在一个transaction中。
public class StudentTest {private static SessionFactory sf=null;@BeforeClasspublic static void beforeClass(){Configuration cfg = new Configuration();cfg.configure();//解析XML文件,不加参数解析classpath下名字为hibernate.cfg.xml文件ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();sf = cfg.buildSessionFactory(sr);}@Testpublic void test() {Student s = new Student();s.setName("lll");s.setAge(11);//Session session = sf.openSession();Session session = sf.getCurrentSession();session.beginTransaction();session.save(s);session.getTransaction().commit();//session.close();}@AfterClasspublic static void afterClass(){sf.close();}}
getCurrentSession需要配置
<property name="current_session_context_class">thread</property>
阅读全文
0 0
- Hibernate——SessionFactory产生session的两种方法
- Hibernate的SessionFactory、Session介绍
- hibernate的sessionFactory和session
- Hibernate的SessionFactory和Session
- Hibernate框架利用sessionFactory保存数据的两种方式
- Hibernate学习笔记——SessionFactory和Session
- [Hibernate系列—] 2. 创建SessionFactory 与 Session
- [Hibernate系列—] 2. 创建SessionFactory 与 Session
- hibernate的创建session的两种方法
- hibernate SessionFactory的获取方法
- hibernate 获取SessionFactory的方法
- 关于Hibernate的Session和SessionFactory
- 关于Hibernate的Session和SessionFactory
- 浅谈hibernate的sessionFactory和session
- 浅谈hibernate的sessionFactory和session
- 浅谈hibernate的sessionFactory和session
- hibernate中SessionFactory,Session的理解?
- hibernate中SessionFactory,Session的理解
- 大话PCIe: 发展与应用
- 子Iframe提交action后父Iframe实现跳转
- 让天堂的归天堂,让尘土的归尘土——谈Linux的总线、设备、驱动模型
- Maven仓库的布局、分类
- ajax消息通信,单文件上传和多文件上传的前后端实现
- Hibernate——SessionFactory产生session的两种方法
- BOS 第一天 maven ssh
- 架构师之路(四)
- python笔记-010-函数(下)
- Climbing Stair爬楼梯算法详解
- 架构师之路(五)
- 【人工智能】图像识别之小白天书——验证码篇(5)
- 关于阿里云Centos服务器搭建Java网站不能访问的问题
- Okhttp3问题 Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported