美文网首页IT@程序员猿媛
mybatis mapper生成流程

mybatis mapper生成流程

作者: nextbeginning | 来源:发表于2019-04-15 18:04 被阅读1次

mybatis提供了一种非常简便的方式去访问数据库,定义接口和sql之后,就能自动帮你完成jdbc操作。这得益于它的mapper机制,本篇文章在于分析mapper的流程。

DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

从mybatis的官方示例代码可以看到,mapper接口的加载是通过Configuration类的addMapper方法去实现的。

public <T> void addMapper(Class<T> type) {
    this.knownMappers.put(type, new MapperProxyFactory(type));
    MapperAnnotationBuilder parser = new MapperAnnotationBuilder(this.config, type);
    parser.parse();
}

可以看到,这里创建了一个MapperProxyFactory对象,当用户调用getMapper方法时,则会调用该factory生成一个基于jdk的代理

public T newInstance(SqlSession sqlSession) {
  final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
  return newInstance(mapperProxy);
}
protected T newInstance(MapperProxy<T> mapperProxy) {
  return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}

最终调用方法时,则是通过MapperProxy的invoke方法完成逻辑调用。

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  final MapperMethod mapperMethod = cachedMapperMethod(method);
  return mapperMethod.execute(sqlSession, args);
}

MapperProxy内部由MapperMethod的execute完成方法调用,该方法调用sqlSession完成操作,即完成了mapper的封装。

if (SqlCommandType.INSERT == command.getType()) {
  Object param = method.convertArgsToSqlCommandParam(args);
  result = rowCountResult(sqlSession.insert(command.getName(), param));
...

相关文章

  • mybatis mapper生成流程

    mybatis提供了一种非常简便的方式去访问数据库,定义接口和sql之后,就能自动帮你完成jdbc操作。这得益于它...

  • Mybatis Generator

    MGB MyBatis Generator 一个生成MyBatis的代码生成器自动生成的mapper.xml文件,...

  • Mybatis

    Mybatis 博客链接 本文主要对Mybatis中启动流程、Mapper解析、Mapper代理、四大对象、SQL...

  • Mybatis

    Mybatis 博客链接 本文主要对Mybatis中启动流程、Mapper解析、Mapper代理、四大对象、SQL...

  • idea常用插件

    Free MyBatis plugin(免费) 常用功能 自动生成 MyBatis 的 dao, mapper, ...

  • 代码生成器 基于SpringCloud SpringBoot M

    代码生成器 基于SpringCloud SpringBoot Mybatis plus VUE 生成Mapper ...

  • MyBatis工作流程

    MyBatis工作流程 MyBatis的几个概念 Mapper配置:可以使用基于XML的Mapper配置文件来实现...

  • IDEA中 spring-boot-mybatis 配置方法(整

    基础配置流程 mybatis-generator生成Mapper代码方法 bug1的解决方法 bug2的解决方法

  • IntelliJ IDEA中 Spring MVC 整合Myba

    通过插件mybatis-generator:generate生成实体类,mapper映射文件、mapper接口文件...

  • mybatis-generator使用

    1、介绍 mybatis-generator 自动生成 mybatis 使用中的xml,model,mapper接...

网友评论

    本文标题:mybatis mapper生成流程

    本文链接:https://www.haomeiwen.com/subject/xgfpwqtx.html