工具类里面一般是静态方法,通过把读取mybatis主配置文件获取SqlSession的一些列繁琐步骤封装成工具类,减少代码量。
Mybatis工具类
src/main/java/com/oxygen/utils/MybatisUtil.java
package com.oxygen.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.InputStream; public class MybatisUtil { private static SqlSessionFactory sqlSessionFactory=null; static { String config="MybatisConfig.xml"; try { InputStream in = Resources.getResourceAsStream(config); sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); } catch (IOException e) { throw new RuntimeException(e); } } public static SqlSession getSqlSession() { SqlSession session = null; if(sqlSessionFactory!=null){ session=sqlSessionFactory.openSession(true); } return session; } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/289076.html