Mybatis工具类MyBatisUtils
作者:互联网
只获取一次sqlSessionFactory,并且用它获取sqlSession,不然每个sql方法的开头都要用这段代码
//myBatis获取sqlSession的工具类
public class MyBatisUtils {
private static SqlSessionFactory factory = null;
//SqlSessionFactory只需要获取一次
static {
try {
//mybatis.xml需要和项目中的文件名一致
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
factory = builder.build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取sqlSession的方法
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
if (factory != null){
sqlSession = factory.openSession();//手动提交事务
//sqlSession = factory.openSession(true);自动提交事务
}
return sqlSession;
}
}
标签:SqlSession,factory,获取,sqlSession,static,Mybatis,工具,null,MyBatisUtils 来源: https://blog.csdn.net/yougcave/article/details/119219799