Mybatis - 工具类

/*获取SqlSession工具类*/
public class SqlSessionFactoryUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static{
        try {
            String resource = "resources/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    我们可以从中获得 SqlSession 的实例。
    SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
    */
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

    /*
    关闭SqlSession
    每次执行完之后,关闭SqlSession
    */
    public void closeSqlSession(SqlSession sqlSession){
        sqlSession.close();
    }
    
    /*增删改:每次都需要提交事务*/
    public void s(SqlSession sqlSession){
        /*提交事务*/
        sqlSession.commit();
    } 
}

 

posted on 2021-12-08 12:23  每天积极向上  阅读(32)  评论(0编辑  收藏  举报

导航