本文主要是介绍mybatis3-SqlSessionFactory保证唯一,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
初始化工具类MyBatisUtil
要保证SqlSessionFaction这个对象全局唯一
导航
回到mybatis导航页
MyBatisUtil.java
package com.torey.mybatis.utils;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.Reader;/*** @ClassName:MyBatisUtils* @Description:创建全局唯一的SqlSessionFaction对象* @author: Torey*/
public class MyBatisUtils {//static是静态的,是属于这个类,而不是属于对象的private static SqlSessionFactory sqlSessionFactory=null;static {//static块用于初始化静态对象try {Reader reader = Resources.getResourceAsReader("mybatis-config.xml");sqlSessionFactory= new SqlSessionFactoryBuilder().build(reader);} catch (IOException e) {e.printStackTrace();//初始化错误,通过抛出ExceptionInInitializerError通知调用者throw new ExceptionInInitializerError(e);}}public static SqlSession openSession(){return sqlSessionFactory.openSession();}public static void closeSession(SqlSession sqlSession){if (null!=sqlSession) {sqlSession.close();}}
}
测试用例
package com.torey.mybatis;import com.torey.mybatis.utils.MyBatisUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;import java.io.File;
import java.io.IOException;
import java.io.Reader;/*** @ClassName:MybatisTestor* @Description:* @author: Torey*/
public class MybatisTestor {@Testpublic void testMyBatisUtil() throws Exception {SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.openSession();Configuration configuration = sqlSession.getConfiguration();System.out.println(configuration);} catch (Exception ex) {throw ex;} finally {MyBatisUtils.closeSession(sqlSession);}}}
导航,上一页,下一页
2SqlSessionFactory
4MyBatis数据查询
支持我-微信扫一扫-加入微信公众号
赞赏作者
这篇关于mybatis3-SqlSessionFactory保证唯一的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!