一、sqlsessionUtils

  1. 由于在执行每个事务时,都要创建一个Sqlsession来执行sql语句
  2. 创建一个工具类,把创建的类打包,也就是SqlsessionFactory
  3. 工具构造方法私有化,为了防止new对象
  4. 所有方法都是静态的,直接采用类名可调用,不用new对象
  5. 在Static静态代码块进行初始化
    static {
            try {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    把SqlsessionFactory打包

    public static SqlSession openSession(){
            return  sqlSessionFactory.openSession();
        }

    返回Selsession

二、工具类使用

  @Test
    public void testInsertCarUtil(){
// 不用new对象 直接调用方法,返回Sqlsession SqlSession sqlSession
= SqlSessionUtil.openSession(); int i = sqlSession.insert("insertCar"); System.out.println(i);
//提交 sqlSession.commit();
// 关闭流 sqlSession.close();