其他分享
首页 > 其他分享> > MybatisUtil

MybatisUtil

作者:互联网

package xx.xx.xx;

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 ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory ssf ;
    static{
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        ssf = new SqlSessionFactoryBuilder().build(is);
    }

    //获取sqlSession对象
    private static SqlSession openSession() throws IOException {
        SqlSession sqlSession = tl.get();
        if(sqlSession==null){
            sqlSession = ssf.openSession();
            tl.set(sqlSession);
        }
        return sqlSession;
    }

    //获取DAO接口实现类对象
    public static Object getMapper(Class clazz) throws IOException {
        return openSession().getMapper(clazz);
    }

    //关闭资源  查询操作
    public static void close() throws IOException {
        openSession().close();
        tl.remove();
    }

    //提交事务  用于增删改操作
    public static void commit() throws IOException {
        openSession().commit();
        close();
    }

    //回滚事务  用于增删改操作
    public static void rollback() throws IOException {
        openSession().rollback();
        close();
    }
}

标签:MybatisUtil,openSession,sqlSession,IOException,import,static,public
来源: https://blog.csdn.net/qq_51218906/article/details/120899340