单例模式创建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
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 ThreadLocaltl = 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(); } } }