Mybatis 创建Configuration对象

Mybatis  创建Configuration对象是在项目启动时就创建了。 具体创建流程为:

https://blog.csdn.net/wolfcode_cn/article/details/80747923

MyBatis的本质是java对数据库的操作。

SqlSessonFactory相当于一个数据库连接池,SqlSession相当于一个数库连接。

Mapper是一个接口,它由SqlSession所创建。

Mybatis-config.xml:   Mybatis配置文件

RoleMapper.java   映射器接口

RoleMapper.xml    映射器XML文件,描述映射关系,SQL等内容。

1:SpringBoot项目中使用默认配置,先读取application.yml中关于Mybatis的配置文件,找到MyBatis-config.xml文件和Mapper.xml文件的位置

mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml   #Mapper所在的配置文件路径,进行扫描
  config-location: classpath:mybatis/mybatis-config.xml  # mybaits-config文件 

Mybatis的运行过程分为两大步:

一:读取配置文件缓存到Configuration对象,用于创建SqlSessionFactory。

二:SqlSession的执行过程。

一:构建SqlSessionFactory过程。

      1: 通过 org.apache.ibatis.builder.xml.XMLConfigBuilder   解析配置的XML文件,读取配置信息存入 org.apache.ibatis.session.Configuration 类对象中。

       2:使用 Configuration 对象去创建  org.apache.ibatis.session.SqlSessionFactory 。  一般创建默认的实现类  DefaultSqlSessionFactory,通过Builder模式创建, Configuration作为统领,一步一步去创建得到Configuration对象。

二:SqlSession的运行过程

      1:有了SqlSessionFactory很容易得到SqlSession ,SqlSession是一个接口,给出了增删改查方法。

public interface SqlSession extends Closeable {

  /**
   * Retrieve a single row mapped from the statement key
   * @param <T> the returned object type
   * @param statement
   * @return Mapped object
   */
  <T> T selectOne(String statement);
}:
     
2:通过SqlSession创建一个Mapper代理对象,一般在service层使用
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//另一种方法
@AutoWired
UserMapper userMapper;
将会调用

public class DefaultSqlSession implements SqlSession {  
  @Override
  public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }

2.1:使用到了configuration的getMapper方法

public class Configuration {  
      public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
         return mapperRegistry.getMapper(type, sqlSession);
      }
}

2.2:使用mapperRegistry的getMapper的方法

public class MapperRegistry { 
 @SuppressWarnings("unchecked")
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
}

2.3:使用mapperProxyFactory.newInstance方法,生成Mapper代理对象。

public class MapperProxyFactory<T> {
  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

}
原文地址:https://www.cnblogs.com/liyafei/p/9334347.html