Mybatis的简单执行流程分析

Mybatis的简单执行流程分析!(小结)


执行流程总览

Mybatis的简单执行流程分析_第1张图片


  1. MyBatis的全局的初始化过程(加载全局核心配置文件)

Mybatis的简单执行流程分析_第2张图片

  1. 创建会话

Mybatis的简单执行流程分析_第3张图片

  1. 获取Mapper实例
  • 从Mapper注册中心获取实例
  • 构建Mapper代理实例

拓展:简单分析注册过程:

  • 在读取核心配置文件config.xml时 。mapper注册器会将所有的 mapper映射 注册添加到内存【即注册中心】中,

  • 注册 mapper 的主要作用是将 Mapper 添加到 knownMappers 集合中,实现 Mapper类 到 Mapper代理工厂 的映射。

  • 将 Mapper类 添加至 注册中心 后还必须完成一次 xml 配置解析(通过MapperAnnotationBuilder进行解析),
    如果解析不成功,那么仍然会将mapper接口移除。

  1. 实现具体的CRUD

  1. 提交事务

sqlSession.commit(),提交事务,事务管理器创建时默认为false,需要手动提交

也可以在创建会话时即可设置 sqlSessionFactory.opensession(autocommit: true)

  1. 关闭会话

sqlSession.close()

测试的实例代码

    //1.初始化信息
    //2.创建默认会话对象( DefaultSqlSession )
    SqlSession sqlSession = MyBatisUtils.getSqlSession();

    //3.从Mapper注册中心获取实例
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

    //4.执行CRUD
    List<User> allUsers = userMapper.getAllUsers();
    userMapper.getUserById(1);
    userMapper.addUser(new User(4, "hello", "hi"));
    userMapper.updateUser(new User(4,"hi","hello"));
    userMapper.deleteUserById(4);

    //5.提交事务
    sqlSession.commit();
    //6.关闭会话
    sqlSession.close();


你可能感兴趣的:(JavaEE)