Hibernate 本身提供了三个管理 Session 对象的方法

  • Session 对象的生命周期与本地线程绑定
  • Session 对象的生命周期与 JTA 事务绑定
  • Hibernate 托付程序管理 Session 对象的生命周期

在 Hibernate 的配置文件里, hibernate.current_session_context_class 属性用于指定 Session 管理方式, 可选值包含
  • thread: Session 对象的生命周期与本地线程绑定
  • jta*: Session 对象的生命周期与 JTA 事务绑定
  • managed: Hibernate 托付程序来管理 Session 对象的生命周期

Session 对象的生命周期与本地线程绑定

假设把 Hibernate 配置文件的 hibernate.current_session_context_class 属性值设为 thread, Hibernate 就会依照与本地线程绑定的方式来管理 Session
Hibernate 按下面规则把 Session 与本地线程绑定
  • 当一个线程(threadA)第一次调用 SessionFactory 对象的 getCurrentSession() 方法时, 该方法会创建一个新的 Session(sessionA) 对象, 把该对象与 threadA 绑定, 并将 sessionA 返回
  • 当 threadA 再次调用 SessionFactory 对象的 getCurrentSession() 方法时, 该方法将返回 sessionA 对象
  • 当 threadA 提交 sessionA 对象关联的事务时, Hibernate 会自己主动flush sessionA 对象的缓存, 然后提交事务, 关闭 sessionA 对象. 当 threadA 撤销 sessionA 对象关联的事务时, 也会自己主动关闭 sessionA 对象
  • 若 threadA 再次调用 SessionFactory 对象的 getCurrentSession() 方法时, 该方法会又创建一个新的 Session(sessionB) 对象, 把该对象与 threadA 绑定, 并将 sessionB 返回


代码具体解释:
HibernateUtils.java(单例)
package com.atguigu.hibernate.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtils { private HibernateUtils(){} private static HibernateUtils instance = new HibernateUtils(); public static HibernateUtils getInstance() {
return instance;
} private SessionFactory sessionFactory; public SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
} public Session getSession(){
return getSessionFactory().getCurrentSession();
} }

DepartmentDao.java

package com.atguigu.hibernate.dao;

import org.hibernate.Session;

import com.atguigu.hibernate.entities.Department;
import com.atguigu.hibernate.hibernate.HibernateUtils; public class DepartmentDao { public void save(Department dept){
//内部获取 Session 对象
//获取和当前线程绑定的 Session 对象
//1. 不须要从外部传入 Session 对象
//2. 多个 DAO 方法也能够使用一个事务!
Session session = HibernateUtils.getInstance().getSession();
System.out.println(session.hashCode()); session.save(dept);
} /**
* 若须要传入一个 Session 对象, 则意味着上一层(Service)须要获取到 Session 对象.
* 这说明上一层须要和 Hibernate 的 API 紧密耦合. 所以不推荐使用此种方式.
*/
public void save(Session session, Department dept){
session.save(dept);
} }

Test

package com.atguigu.hibernate.test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List; import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.jdbc.Work;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.atguigu.hibernate.dao.DepartmentDao;
import com.atguigu.hibernate.entities.Department;
import com.atguigu.hibernate.entities.Employee;
import com.atguigu.hibernate.hibernate.HibernateUtils; public class HibernateTest { private SessionFactory sessionFactory;
private Session session;
private Transaction transaction; @Before
public void init(){
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry =
new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry); session = sessionFactory.openSession();
transaction = session.beginTransaction();
} @After
public void destroy(){
transaction.commit();
session.close();
sessionFactory.close();
} @Test
public void testManageSession(){ //获取 Session
//开启事务
Session session = HibernateUtils.getInstance().getSession();
System.out.println("-->" + session.hashCode());
Transaction transaction = session.beginTransaction(); DepartmentDao departmentDao = new DepartmentDao(); Department dept = new Department();
dept.setName("ATGUIGU"); departmentDao.save(dept);
departmentDao.save(dept);
departmentDao.save(dept); //若 Session 是由 thread 来管理的, 则在提交或回滚事务时, 已经关闭 Session 了.
transaction.commit();
System.out.println(session.isOpen());
} }

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?

>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory> <!-- Hibernate 连接数据库的基本信息 -->
<property name="connection.username">scott</property>
<property name="connection.password">java</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <!-- Hibernate 的基本配置 -->
<!-- Hibernate 使用的数据库方言 -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <!-- 执行时是否打印 SQL -->
<property name="show_sql">true</property> <!-- 执行时是否格式化 SQL -->
<property name="format_sql">true</property> <!-- 生成数据表的策略 -->
<property name="hbm2ddl.auto">update</property> <!-- 设置 Hibernate 的事务隔离级别 -->
<property name="connection.isolation">2</property> <!-- 删除对象后, 使其 OID 置为 null -->
<property name="use_identifier_rollback">true</property> <!-- 配置 C3P0 数据源 -->
<!--
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="c3p0.acquire_increment">2</property> <property name="c3p0.idle_test_period">2000</property>
<property name="c3p0.timeout">2000</property> <property name="c3p0.max_statements">10</property>
--> <!-- 设定 JDBC 的 Statement 读取数据的时候每次从数据库中取出的记录条数 -->
<property name="hibernate.jdbc.fetch_size">100</property> <!-- 设定对数据库进行批量删除,批量更新和批量插入的时候的批次大小 -->
<property name="jdbc.batch_size">30</property> <!-- 启用二级缓存 -->
<property name="cache.use_second_level_cache">true</property> <!-- 配置使用的二级缓存的产品 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <!-- 配置启用查询缓存 -->
<property name="cache.use_query_cache">true</property> <!-- 配置管理 Session 的方式 -->
<property name="current_session_context_class">thread</property> <!-- 须要关联的 hibernate 映射文件 .hbm.xml -->
<mapping resource="com/atguigu/hibernate/entities/Department.hbm.xml"/>
<mapping resource="com/atguigu/hibernate/entities/Employee.hbm.xml"/> <class-cache usage="read-write" class="com.atguigu.hibernate.entities.Employee"/>
<class-cache usage="read-write" class="com.atguigu.hibernate.entities.Department"/>
<collection-cache usage="read-write" collection="com.atguigu.hibernate.entities.Department.emps"/>
</session-factory>
</hibernate-configuration>

版权声明:本文博主原创文章。博客,未经同意不得转载。

hibernate 管理 Session(单独使用session,不spring)的更多相关文章

  1. hibernate 管理 Session(单独使用session,非spring)

    Hibernate 自身提供了三种管理 Session 对象的方法 Session 对象的生命周期与本地线程绑定 Session 对象的生命周期与 JTA 事务绑定 Hibernate 托付程序管理 ...

  2. 为什么要用Hibernate框架? 把SessionFactory,Session,Transcational封装成包含crud的工具类并且处理了事务,那不是用不着spring了?

    既然用Hibernate框架访问管理持久层,那为何又提到用Spring来管理以及整合Hibernate呢?把SessionFactory,Session,Transcational封装成包含crud的 ...

  3. Hibernate管理Session和批量操作

    Hibernate管理Session Hibernate自身提供了三种管理Session对象的方法 Session对象的生命周期与本地线程绑定 Session对象的生命周期与JTA事务绑定 Hiber ...

  4. Spring与Hibernate集成中的Session问题

    主要讨论Spring与Hibernate集成中的session问题 1.通过getSession()方法获得session进行操作 public class Test extends Hibernat ...

  5. 框架Hibernate笔记系列 基础Session

    标题:框架Hibernate笔记 资料地址: 1. www.icoolxue.com 孔浩 1.背景简介 Hibenate是JBoss公司的产品.它是数据持久化的框架.Usually,我们使用JDBC ...

  6. 浅谈hibernate的sessionFactory和session

    一.hibernate是什么? Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库. Hiber ...

  7. 面试题:hibernate 第二天 快照 session oid 有用

    ## Hibernate第二天 ## ### 回顾与反馈 ### Hibernate第一天 1)一种思想 : ORM OM(数据库表与实体类之间的映射) RM 2)一个项目 : CRM 客户关系管理系 ...

  8. 79. could not initialize proxy - no Session 【从零开始学Spring Boot】

    [原创文章,转载请注明出处] Spring与JPA结合时,如何解决懒加载no session or session was closed!!! 实际上Spring Boot是默认是打开支持sessio ...

  9. Spring Session解决Session共享

    1. 分布式Session共享   在分布式集群部署环境下,使用Session存储用户信息,往往出现Session不能共享问题.   例如:服务集群部署后,分为服务A和服务B,当用户登录时负载到服务A ...

随机推荐

  1. MYSQL,innodb_buffer_pool_size内存分配

    为MYSQL.innodb_buffer_pool_size=8G.MySQL一起动就会将占用掉8G内存(觉得TOP能够看到内存被使用了8G),可是近期才细致研究一下.原来不是这种(可能自己对Linu ...

  2. sublime配置攻略

    大家好,今天给大家分享的编辑器:sublime text2     我用过非常多编辑器, EditPlus.EmEditor.Notepad++.Notepad2.UltraEdit.Editra.V ...

  3. 【Linux】lvm基础操作

    新增两块硬盘,来进行实验: [root@jp ~]# fdisk -l Disk /dev/sda: 107.3 GB, 107374182400 bytes 255 heads, 63 sector ...

  4. JAVA编程思想(2) - 操作符(一)

    "在最底层,Java中的数据是通过操作符来操作的." 1. 使用Java操作符 -操作符接受一个或者多个參数,并生成一个新值,參数的形式与普通的方法调用不用,但效果是同样的.加号和 ...

  5. 微信小程序开发者工具集合包

    开发论坛 http://www.henkuai.com/forum-56-1.html 工具包下载  https://yunpan.cn/ckXFpuzAeVi2s  访问密码 b4cc 开发文档 h ...

  6. 跟我extjs5(03--在项目过程中加载文件)

    跟我extjs5(03--在项目过程中加载文件) 上一节中用sencha工具自己主动创建了一个项目.而且能够在浏览器中查看. 如今我们来看看js类载入过程. 例如以下图所看到的: watermark/ ...

  7. OpenJDK 阅读源代码 Java 实现字节流输入类

    Java 的输入输出总是给人一种非常混乱的感觉.要想把这个问题搞清楚.必须对各种与输入输出相关的类之间的关系有所了解. 仅仅有你了解了他们之间的关系.知道设计这个类的目的是什么.才干更从容的使用他们. ...

  8. Cocos2d-x 如何输出 Android用电话 腰带Tag的Log刊物

    于Cocos2d-x根据代码 #if(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #define LOGAnroid( ...) #else if (CC_TAR ...

  9. 接近带给你AngularJS - 经验说明示例

    接近带给你AngularJS列: 带你走近AngularJS - 基本功能介绍 带你走近AngularJS - 体验指令实例 带你走近AngularJS - 创建自己定义指令 ------------ ...

  10. VS2015 C#6.0

    VS2015 C#6.0 中的那些新特性 VS2015在自己机器上确实是装好了,(全部安装的话,在Java SE 开发工具包 会卡顿很长时间,我直接关闭,然后重启电脑,重新修复安装搞定), 想来体验一 ...