在每次测试的时候,都要创建SqlSessionFactory对象,对内耗巨大。
设计一个工具类,使SqlSessionFactory,只创建一次。
1-编写MyBatisUtil工具类
package cn.smbms.util;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.InputStream;public class MyBatisUtil {private static SqlSessionFactory sqlSessionFactory;//创建SqlSessionFactory,只创建一次static{//在静态代码块下,只创建一次try {InputStream inputStream = Resources.getResourceAsStream(\"mybatis-config.xml\");sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}//创建sqlSession对象public static SqlSession createSqlSession(){return sqlSessionFactory.openSession(false);//事务需要手动提交 true:系统自动帮你提交}//关闭sqlSession对象public static void closeSqlSession(SqlSession sqlSession){sqlSession.close();}}
2-测试类使用该工具类
package cn.smbms.dao.user;import cn.smbms.pojo.User;import cn.smbms.util.MyBatisUtil;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 org.apache.log4j.Logger;import org.junit.Test;import java.io.IOException;import java.io.InputStream;import java.util.List;public class UserMapperTest {//创建logger对象,进行日志输出private static Logger logger=Logger.getLogger(UserMapperTest.class);@Testpublic void test1(){SqlSession sqlSession = MyBatisUtil.createSqlSession();//方法一int count = sqlSession.selectOne(\"cn.smbms.dao.user.UserMapper.count\");//方法二int count = sqlSession.getMapper(UserMapper.class).count();logger.debug(\"UserMapperTest test1 count:\"+count);MyBatisUtil.closeSqlSession(sqlSession);}}