因为每次测试都西药读取mybatis-config.xml根配置文件,然后有需要重复创建SqlSessionFactory和SqlSession,这样的操作比较频繁。所以也想Hibernate一样。开发一个工厂类封装以上的重复代码...
package com.test; 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 MybatisUtils { //初始化创建SqlSessionFactory private static SqlSessionFactory sqlSessionFactory = null; static{ try{ //读取mybaits-config.xml文件 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); }catch(Exception e){ e.printStackTrace(); } } //获取SqlSession public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } //获取SqlSessionFactory public static SqlSessionFactory getSessionFactory(){ return sqlSessionFactory; } }