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. 问题 B: 小鱼的搭配购物(并查集+01背包)
  2. WebClient UI忽略所有增强的开关
  3. Java面向对象设计原则
  4. mysql 5.7 密码过期_mysql5.7 密码过期了怎么办
  5. yolov3训练误差可视化
  6. 病毒——隐藏鸟 系统文件夹不见了
  7. lua OOP实现对象的链式调用
  8. windows安装JDK步骤
  9. Flash Bootloader
  10. apt-get update 更新失败----如何清除破损而且陈旧的PPA仓库 (W: Failed to fetch http://ppa.launchpad.net/jonathonf/pyt)
  11. 探索学习 Vue 组件篇 第二篇 组件类型:非单文件组件
  12. yar php使用,php的轻量级rpc框架yar
  13. Android的apk安装时签名相同冲突解决
  14. 智汀双管齐下,玩转米家HomeKit智能家居
  15. ios开发之autolayout 第三方框架Masonry
  16. EXCEL技巧——EXCEL如何实现隔行隔列求和
  17. 鱼眼镜头的标定及矫正
  18. cuda、cudnn和pytorch下载与安装的经验
  19. HTML 表单-表单域
  20. 精品微信小程序中医药配方小程序药方+后台系统|前后分离VUE

热门文章

  1. 2019年中国工业机器人首次出口数量大于进口数量
  2. Linux系统下GCC编译错误:“undefined reference to ‘sqrt‘”
  3. 贪吃蛇游戏的C++代码
  4. java class.getmethod_java反射之Class.getMethod与getDeclaredMethods()区别
  5. word邮件合并一页8个_办公软件小课堂||word邮件合并
  6. c语言中一百以内相乘的积,一百以内的加减乘除法游戏....
  7. Tomcat的Classpath-常见问题以及如何解决
  8. 050_学习的CSS属性
  9. 046_CSS3动画
  10. 020_html格式化