2021.3.22

编写mybatis工具类

这个工具类,只要在mybatis相关的地方都需要调用他,建议写成static直接调用

在标记为sources的文件夹中创建包,编写工具类

//sqlSessionFactory --> sqlSession
public class MybatisUtils {

static SqlSessionFactory sqlSessionFactory = null;

static {
try {
//使用Mybatis第一步 :获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}

//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例.
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}

原文地址:https://www.cnblogs.com/buxiang-Christina/p/14908095.html