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

Mybatis单例模式

来源:互联网 收集:自由互联 发布时间:2021-07-03
单例模式创建sqlSessionFactory package orc.jxnd.tools;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.SqlSessionFa
单例模式创建sqlSessionFactory
package orc.jxnd.tools;

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 Tools {

	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 session = tl.get(); if(session==null){ session = sqlSessionFactory.openSession(); tl.set(session); } return session; } public static void closeSqlSession(){ SqlSession session = tl.get(); if(session!=null){ tl.set(null); session.close(); } } public static void commit(){ SqlSession sqlSession=tl.get(); if (sqlSession !=null) { tl.set(null); sqlSession.commit(); } } public static void rollBack(){ SqlSession sqlSession=tl.get(); if (sqlSession !=null) { tl.set(null); sqlSession.rollback(); } } }
  
 
网友评论