初始化工具类MyBatisUtil
要保证SqlSessionFaction这个对象全局唯一
导航
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 {
@Test
public 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数据查询