mybatis

mybatis-spring 基于xml配置原理介绍

2020-07-26  本文已影响0人  晴天哥_王志

系列

开篇

核心逻辑

SqlSessionTemplate
public class SqlSessionTemplate implements SqlSession, DisposableBean 

Demo

public interface UserMapper {
  @Select("SELECT * FROM users WHERE id = #{userId}")
  User getUser(@Param("userId") String userId);
} 

<! -- 开启事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <constructor-arg ref="dataSource" />
</bean>

<! -- 定义sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="mapperLocations" value="classpath*:sample/config/mappers/**/*.xml" />
</bean>

<! -- 定义DAO对象 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

SqlSessionFactoryBean

public interface FactoryBean<T> {
    String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";

    @Nullable
    T getObject() throws Exception;

    @Nullable
    Class<?> getObjectType();

    default boolean isSingleton() {
        return true;
    }
}
public class SqlSessionFactoryBean
    implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {

  @Override
  public SqlSessionFactory getObject() throws Exception {
    if (this.sqlSessionFactory == null) {
      afterPropertiesSet();
    }

    return this.sqlSessionFactory;
  }

  public void afterPropertiesSet() throws Exception {
    this.sqlSessionFactory = buildSqlSessionFactory();
  }


  protected SqlSessionFactory buildSqlSessionFactory() throws Exception {

    final Configuration targetConfiguration;

    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configuration != null) {
      targetConfiguration = this.configuration;
      if (targetConfiguration.getVariables() == null) {
        targetConfiguration.setVariables(this.configurationProperties);
      } else if (this.configurationProperties != null) {
        targetConfiguration.getVariables().putAll(this.configurationProperties);
      }
    } else if (this.configLocation != null) {
      xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
      targetConfiguration = xmlConfigBuilder.getConfiguration();
    } else {
      // 创建Configuration对象
      targetConfiguration = new Configuration();
      Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
    }

    // 省略相关代码

    if (this.mapperLocations != null) {
      if (this.mapperLocations.length == 0) {
      } else {
        for (Resource mapperLocation : this.mapperLocations) {
          try {
            // 通过XMLMapperBuilder来进行解析
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
            // 通过parse将配置解析到Configuration对象当中
            xmlMapperBuilder.parse();
          } catch (Exception e) {
          } finally {
            ErrorContext.instance().reset();
          }
        }
      }
    } 

    // 返回DefaultSqlSessionFactory对象。
    return this.sqlSessionFactoryBuilder.build(targetConfiguration);
  }
}

MapperFactoryBean

SqlSessionDaoSupport

public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {}

public abstract class SqlSessionDaoSupport extends DaoSupport {

  private SqlSessionTemplate sqlSessionTemplate;

  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    if (this.sqlSessionTemplate == null || sqlSessionFactory != this.sqlSessionTemplate.getSqlSessionFactory()) {
      this.sqlSessionTemplate = createSqlSessionTemplate(sqlSessionFactory);
    }
  }

  protected SqlSessionTemplate createSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}

SqlSessionTemplate

public class SqlSessionTemplate implements SqlSession, DisposableBean {
  // sqlSessionFactory是DefaultSqlSessionFactory
  private final SqlSessionFactory sqlSessionFactory;
  private final ExecutorType executorType;
  private final SqlSession sqlSessionProxy;
  private final PersistenceExceptionTranslator exceptionTranslator;

  public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
      PersistenceExceptionTranslator exceptionTranslator) {

    this.sqlSessionFactory = sqlSessionFactory;
    this.executorType = executorType;
    this.exceptionTranslator = exceptionTranslator;
    this.sqlSessionProxy = (SqlSession) newProxyInstance(SqlSessionFactory.class.getClassLoader(),
        new Class[] { SqlSession.class }, new SqlSessionInterceptor());
  }
}
public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {

  public T getObject() throws Exception {
    return getSqlSession().getMapper(this.mapperInterface);
  }
}


public abstract class SqlSessionDaoSupport extends DaoSupport {
  public SqlSession getSqlSession() {
    return this.sqlSessionTemplate;
  }
}
public class SqlSessionTemplate implements SqlSession, DisposableBean {
  // 注入的DefaultSqlSessionFactory对象
  private final SqlSessionFactory sqlSessionFactory;
  private final ExecutorType executorType;
  private final SqlSession sqlSessionProxy;
  private final PersistenceExceptionTranslator exceptionTranslator;

  public <T> T getMapper(Class<T> type) {
    return getConfiguration().getMapper(type, this);
  }

  public Configuration getConfiguration() {
    return this.sqlSessionFactory.getConfiguration();
  }
}

参考文档

上一篇下一篇

猜你喜欢

热点阅读