简化代码,实现一个静态的工具类来实现获取SqlSession
主要有getSqlSessionFactory()和getSqlSession()
public class MybatisUtil { private static SqlSessionFactory sqlSessionFactory; /**
* 构建SqlSessionFactory工厂
*/
public static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory==null){ try {
//通过配置文件获取输入流
InputStream inputStream=Resources.getResourceAsStream("mybatis-config.xml");
//通过Builder和输入流构建sqlSessionFactory工厂
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
} }
return sqlSessionFactory;
} /**
* 获取sqlSession
*/
public static SqlSession getSqlSession(){
return getSqlSessionFactory().openSession();
}
}