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

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;@Beforepublic 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();}@Afterpublic void destroy(){transaction.commit();session.close();sessionFactory.close();}@Testpublic 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>

posted on 2017-06-02 18:58 mthoutai 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/mthoutai/p/6934796.html

hibernate 管理 Session(单独使用session,非spring)相关推荐

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

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

  2. 5G NGC — 会话管理模型 — PDU Session

    目录 文章目录 目录 5G 的会话管理模型 PDU Session PDU Session 的类型 Ethernet Type Unstructured Type DNN 的作用 UE IP 地址的分 ...

  3. Externalizing Session State for a Spring Boot Application Using Spring-Session

    为什么80%的码农都做不了架构师?>>>    Spring-session is a very cool new project that aims to provide a si ...

  4. springsecurity sessionregistry session共享_不用 Spring Security 可否?试试这个小而美的安全框架...

    写在前面 在一款应用的整个生命周期,我们都会谈及该应用的数据安全问题.用户的合法性与数据的可见性是数据安全中非常重要的一部分.但是,一方面,不同的应用对于数据的合法性和可见性要求的维度与粒度都有所区别 ...

  5. Spring Session实现Session共享入门教程

    Web中的Session和Cookie回顾 1. Session机制 由于HTTP协议是无状态的协议,一次浏览器和服务器的交互过程就是: 浏览器:你好吗? 服务器:很好! 这就是一次会话,对话完成后, ...

  6. 会话管理-2.1.Session介绍

    1.Session是什么? 客户端浏览器访问服务器的时候,服务器把客户端信息以某种形式记录在服务器上.这就是Session. 客户端浏览器再次访问时只需要从该Session中查找该客户的状态就可以了, ...

  7. Spring的工具类,方便在非spring管理环境中获取bean

    场景 在SpringBoot的后台项目中,如果想要引入并且调用某个bean,可以直接通过注解的方式. 比如在单元测试中引入某业务的Controller @RunWith(SpringJUnit4Cla ...

  8. Spring Session官方介绍及spring框架学习方法

    现在我们开始讲Spring Session,首先进入maven中央仓库,在百度查一下,如何替换成阿里云的仓库就OK了,我们搜索什么呢,spring-session-data-redis,这里面找到这个 ...

  9. spring管理的类如何调用非spring管理的类

    spring管理的类如何调用非spring管理的类. 就是使用一个spring提供的感知概念,在容器启动的时候,注入上下文即可. 下面是一个工具类. 1 import org.springframew ...

最新文章

  1. 使用 Circular Reveal 动画让页面跳转更炫酷
  2. php开发ftp服务器搭建教程,在Linux中搭建一个FTP服务器
  3. levedb 导入 mysql_LevelDB-初始篇
  4. 世界坐标系到观察坐标系的变换步骤_shader观察(像机)矩阵变换的一己之见
  5. 亲临ACM MM大会现场,围观各路技术高手参会心得
  6. 微软放弃继续开发 Visual Basic !
  7. 【随机森林】深入浅出讲解随机森林算法
  8. 修改最新版谷歌浏览器编码方式
  9. 关于机器人方面的sci论文_机器人领域国际期刊(SCI收录)
  10. nginx代理安装ssl证书
  11. “十步杀一人,千里不留行。事了拂衣去,深藏功与名。”
  12. 知道一点怎么设直线方程_两点直线方程怎么求
  13. 跨品种套利 - 期货
  14. 小程序 加快安卓手机向蓝牙设备发送大数据
  15. 在北京开公司,搬家后如何变更税务和工商?
  16. mysql五日均线_中国股市:一根“5日均线”走天下,线上买,线下卖,简直了!...
  17. 类似 毕克BYK346 有机硅基材润湿剂 上海荟研 水性木器漆,水性工业漆 油墨体系 光固化体系
  18. 自动生成图片及修改图片尺寸
  19. Linux系统下的一些常用基本命令
  20. soi cmos技术及其应用_投屏技术及其教学应用

热门文章

  1. java配置接口提供给vue,vue在js中配置全局API接口
  2. import java.util.calendar_Java.util.Calendar.setTimeInMillis()
  3. php音译汉字,PHP中的西里尔语音译
  4. 科沃斯机器人电池激活_扫地机器人充不进去电怎么办
  5. idea中build项目之后生成的target看不见
  6. idea 代码自动补全快捷键
  7. 给定一个排序好的数组,插入一个数,使其仍然有规律不使用排序算法
  8. 100_框架对象事件
  9. 024_Jedis连接池
  10. python fun_一道神奇的Python面试题,你会吗?