import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.Null;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* MyBatis工具类
* @author Administrator
*
*/
public class SqlUtils {
private static SqlSessionFactory sFactory; //对象工厂
private static ThreadLocal<SqlSession> threadLocals = new ThreadLocal<>(); //将会话放到线程里
static{
try {
//加载配置文件
InputStream iStream = Resources.getResourceAsStream("config/mybatis-config.xml");
//获得对象工厂
sFactory = new SqlSessionFactoryBuilder().build(iStream);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
throw new RuntimeException("Mybatis Utils 工具类读取配置文件出现异常");
}
}
//获得session会话
private static SqlSession getOpenSession(){
SqlSession session = threadLocals.get();
if (session == null) {
session = sFactory.openSession();
threadLocals.set(session);
}
return session;
}
//获取接口的实现类对象
public static Object getMapper(Class ca){
SqlSession session = getOpenSession();
//获取dao接口的实现类
return session.getMapper(ca);
}
//关闭资源链接
public static void close(){
SqlSession session = getOpenSession();
session.close();
threadLocals.remove();
}
//提交事务
public static void commit(){
getOpenSession().commit();
close();
}
//回滚
public static void rollback(){
getOpenSession().rollback();
close();
}
}
MyBatis工具类
最新推荐文章于 2022-07-24 18:00:31 发布