【MyBatis】MybatisUtil工具类的作用(五)
来源:互联网 发布:开源人工智能语音系统 编辑:程序博客网 时间:2024/05/16 14:18
1)在静态初始化块中加载mybatis配置文件和StudentMapper.xml文件一次
2)使用ThreadLocal对象让当前线程与SqlSession对象绑定在一起
3)获取当前线程中的SqlSession对象,如果没有的话,从SqlSessionFactory对象中获取SqlSession对象
4)获取当前线程中的SqlSession对象,再将其关闭,释放其占用的资源
/** * 工具类 * @author LFSenior */public class MybatisUtil {private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();private static SqlSessionFactory sqlSessionFactory;/** * 加载位于src/mybatis.xml配置文件 */static{try {Reader reader = Resources.getResourceAsReader("mybatis.xml");sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);} catch (IOException e) {e.printStackTrace();throw new RuntimeException(e);}}/** * 禁止外界通过new方法创建 */private MybatisUtil(){}/** * 获取SqlSession */public static SqlSession getSqlSession(){//从当前线程中获取SqlSession对象SqlSession sqlSession = threadLocal.get();//如果SqlSession对象为空if(sqlSession == null){//在SqlSessionFactory非空的情况下,获取SqlSession对象sqlSession = sqlSessionFactory.openSession();//将SqlSession对象与当前线程绑定在一起threadLocal.set(sqlSession);}//返回SqlSession对象return sqlSession;}/** * 关闭SqlSession与当前线程分开 */public static void closeSqlSession(){//从当前线程中获取SqlSession对象SqlSession sqlSession = threadLocal.get();//如果SqlSession对象非空if(sqlSession != null){//关闭SqlSession对象sqlSession.close();//分开当前线程与SqlSession对象的关系,目的是让GC尽早回收threadLocal.remove();}}}
阅读全文
1 0
- 【MyBatis】MybatisUtil工具类的作用(五)
- mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现
- Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
- MyBatis笔记---开发环境搭建、xml配置以及MybatisUtil工具类创建
- MyBatisUtil.java.工具类,连接数据库库
- MyBatisUtil
- MyBatisUtil
- MyBatisUtil
- MyBatisUtil
- MyBatis入门实例 ——MyBatisUtil.java
- MyBatis基本环境搭建与MyBatisUtil
- mybatis系列五:mybatis代码生成工具
- MyBatis的工具类SqlSession
- MyBatis工具类的封装
- SharedPreferencesUtil 工具类的作用
- mybatis的selectKey作用
- Mybatis selectkey 的作用
- 深入理解MyBatis(五)—MyBatis的插件机制
- 腾讯2017暑期实习生编程题:算法基础-字符移位 [python]
- 企业招聘:UX设计师需要满足他们哪些期望?
- SparkStreaming之滑动窗口的实现
- HTML JavaScript Vue 编辑器推荐
- Cassandra的安装与集群部署
- 【MyBatis】MybatisUtil工具类的作用(五)
- 《设计模式》学习笔记4——抽象工厂模式
- python基础-abstractmethod、__属性、property、setter、deleter、classmethod、staticmethod
- phpBasic
- 教程篇(5.4) NSE4 15. 高可用性 ❀ 飞塔 (Fortinet) 网络安全专家
- Retrofit的二次封装
- Linux下的tar压缩解压缩命令详解
- codeforce Vladik and Complicated Book
- html 布局