package self.exercise.utils;
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;
import org.apache.log4j.Logger;
public final class MyBatisUtil{ private final static String PATH = "<核心配置文件的路径>";
private final static Logger logger = Logger.getLogger(MyBatisUtil.class);
private static InputStream inputStream;
private SqlSessionFactory sqlSessionFactory;
private MyBatisUtil(){}
static{
try{
//获取配置文件的位置
inputStream = new Resources.getResourceAsStream(PATH);
//从配置文件构建SqlSessionFactory对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e) {
logger.debug("加载文件异常:" + e.getMessage());
throw new RuntimeException("加载文件异常:" + e.getMessage());
}
}
/**
* <p> 描述:获取SqlSession对象</p>
* @return
*/
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
/**
* <p> 描述:关闭SqlSession对象</p>
* @return
*/
public static void closeSqlSession(SqlSession sqlSession){
if(sqlSession != null){
sqlSession.close();
}
}
}
将MyBatisUtil类加上final修饰,不然其他类继承;将构造函数私有化,不允许实例化对象。