当前位置 : 主页 > 编程语言 > c++ >

并发情况下SqlSession的开和关

来源:互联网 收集:自由互联 发布时间:2021-07-03
DBTool.java package org.jxnd.tool;import java.io.IOException;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.i
DBTool.java
package org.jxnd.tool;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DBtools {
	private static SqlSessionFactory sqlSessionFactory;
	private static final String resource = "mybatis.xml";
	private static ThreadLocal
 
   tl = new ThreadLocal
  
   (); static{ try { InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //SqlSession不能使用单例,sqlSessionFactory可以使用单例 public static SqlSession getSqlSession(){ //从本地线程为获取一个绑定的sqlSession资源 SqlSession sqlSession = tl.get(); if(sqlSession == null){ sqlSession = sqlSessionFactory.openSession(); //将此sqlSession设到本地线程中 tl.set(sqlSession); } return sqlSession; } //关闭sqlSession资源 public static void closeSqlSession(){ SqlSession sqlSession = tl.get(); if(sqlSession != null){ tl.set(null); sqlSession.close(); } } //sqlSession提交 public static void commit(){ SqlSession sqlSession = tl.get(); if(sqlSession != null){ tl.set(null); sqlSession.commit(); } } //sqlSession回滚 public static void rollback(){ SqlSession sqlSession = tl.get(); if(sqlSession != null){ tl.set(null); sqlSession.rollback(); } } } 在本地线程为每一个SqlSession绑定一个资源,避免系统的堆积爆炸。
  
 
网友评论