• Mybatis与spring整合原理


    1、mybatis的缓存机制

      mybatis的缓存采用包装器模式,统一实现Cache接口,基础实现类PerpetualCache。使用Map<Object,Object> cache作为存储结构。

    (1)一级缓存

      一级缓存作用域是SqlSession,也就是一次数据库连接会话,其被定义在SqlSession->Executor->PerpetualCache。

      一级缓存时执行commit,close,增删改等操作,就会清空当前的一级缓存;当对SqlSession执行更新操作(update、delete、insert)后并执行commit时,不仅清空其自身的一级缓存(执行更新操作的效果),也清空二级缓存(执行commit()的效果)。

      参考文章:https://mp.weixin.qq.com/s/4Puee_pPCNArkgnFaYlIjg

    (2)二级缓存

      二级缓存作用域是namespace,也就是一个mapper会拥有一个二级缓存。二级缓存是通过装饰器模式对Executor进行包装——CachingExecutor。

      开启了二级缓存后,如果要使用其他非内存介质的存储需要将pojo实现Serializable接口,为了将缓存数据取出执行反序列化操作。

      二级缓存的开启:在mybatis-config.xml中设置总开关,然后再mapper中设置<cache/>

    <settings>
        <setting name="cacheEnabled" value="true" />
    </settings>

    (3)二级缓存的存储和清除

      只有当前的session.close()时,该session的中一级缓存的数据才会存入二级缓存,在同一session下时,因为没有执行.close()关闭session,所以不会将数据存入二级缓存。

      commit和close对二级缓存的影响:https://blog.csdn.net/jinbaizhe/article/details/81158514

       参考文章:https://www.cnblogs.com/cxuanBlog/p/11333021.html

    2、mybatis与spring整合

    1.1、mybatis在使用时的执行流程

      ——首先创建SqlSessionFactory,SqlSessionFactory解析全局配置文件(mybatis-config.xml)和对应的Mapper文件

      ——SqlSessionFactory通过openSession()获取一个SqlSession,一个SqlSession表示一次会话

      ——SqlSession通过getMapper(xx.class)获取相应的mapper对象。

    1.2、与spring整合时各个类是如何创建的

      ——首先看SqlSessionFactory的创建:    

    SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent>

        SqlSessionFactoryBean实现InitializingBean,在Bean初始化过程中当属性注入结束后,调用afterPropertiesSet()

    @Override
      public void afterPropertiesSet() throws Exception {
        notNull(dataSource, "Property 'dataSource' is required");
        notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
        state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
                  "Property 'configuration' and 'configLocation' can not specified with together");
    
        this.sqlSessionFactory = buildSqlSessionFactory();
      }

        在afterPropertiesSet()中解析全局配置文件和Mapper文件,创建SqlSessionFactory。

        SqlSessionFactoryBean实现FactoryBean,是通过getObject()来获取实例对象的,其也是调用afterPropertiesSet()。

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

        SqlSessionFactoryBean实现ApplicationListener,是监听spring上下文刷新事件,保证Mapper问价加载完毕。

    @Override
      public void onApplicationEvent(ApplicationEvent event) {
        if (failFast && event instanceof ContextRefreshedEvent) {
          // fail-fast -> check all statements are completed
          this.sqlSessionFactory.getConfiguration().getMappedStatementNames();
        }
      }

      ——SqlSession的创建:原生的SqlSession有一个默认实现类DefaultSqlSession,其是线程不安全的,所以每次会话都要创建一个新的DefaultSqlSession,整合Spring后,使用SqlSessionTemplate替代原生的DefaultSqlSession,其通过JDK动态代理的方式,在每次调用相应方法时都去创建一个SqlSession,也就是将SqlSession的创建放在了代理类的invoke方法中:SQLSessionTemplate是为了解决线程安全问题。

    public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
          PersistenceExceptionTranslator exceptionTranslator) {
    
        notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
        notNull(executorType, "Property 'executorType' is required");
    
        this.sqlSessionFactory = sqlSessionFactory;
        this.executorType = executorType;
        this.exceptionTranslator = exceptionTranslator;
        this.sqlSessionProxy = (SqlSession) newProxyInstance(
            SqlSessionFactory.class.getClassLoader(),
            new Class[] { SqlSession.class },
            new SqlSessionInterceptor());
      }
    private class SqlSessionInterceptor implements InvocationHandler {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          SqlSession sqlSession = getSqlSession(
              SqlSessionTemplate.this.sqlSessionFactory,
              SqlSessionTemplate.this.executorType,
              SqlSessionTemplate.this.exceptionTranslator);
          try {
            Object result = method.invoke(sqlSession, args);
            if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
              // force commit even on non-dirty sessions because some databases require
              // a commit/rollback before calling close()
              sqlSession.commit(true);
            }
            return result;
          } catch (Throwable t) {
            Throwable unwrapped = unwrapThrowable(t);
            if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
              // release the connection to avoid a deadlock if the translator is no loaded. See issue #22
              closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
              sqlSession = null;
              Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
              if (translated != null) {
                unwrapped = translated;
              }
            }
            throw unwrapped;
          } finally {
            if (sqlSession != null) {
              closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
            }
          }
        }
      }

      事务是由spring进行管理的,在getSession时,通过SqlSessionHolder进行获取,TransactionSynchronizationManager实际就是一系列ThreadLocal的封装。

    public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {
    
        notNull(sessionFactory, NO_SQL_SESSION_FACTORY_SPECIFIED);
        notNull(executorType, NO_EXECUTOR_TYPE_SPECIFIED);
    
        SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    
        SqlSession session = sessionHolder(executorType, holder);
        if (session != null) {
          return session;
        }
    
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug("Creating a new SqlSession");
        }
    
        session = sessionFactory.openSession(executorType);
    
        registerSessionHolder(sessionFactory, executorType, exceptionTranslator, session);
    
        return session;
      }

      ——如何通过SqlSessionTemplate去获取对应的Mapper代理类。

      SqlSessionTemplate的使用是通过SqlSessionDaoSupport去使用的,SqlSessionDaoSupport中会注入SqlSessionTemplate:

    public abstract class SqlSessionDaoSupport extends DaoSupport {
    
      private SqlSession sqlSession;
    
      private boolean externalSqlSession;
    
      public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        if (!this.externalSqlSession) {
          this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
        }
      }
    
      public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSession = sqlSessionTemplate;
        this.externalSqlSession = true;
      }

      初始化过程如下:

    (1)定义MapperScanner

    public class MapperScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware

      MapperScannerConfigurer实现BeanDefinitionRegistryPostProcessor,其void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)方法是在bean注册时修改bean的定义:

    @Override
      public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        if (this.processPropertyPlaceHolders) {
          processPropertyPlaceHolders();
        }
    
        ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
        scanner.setAddToConfig(this.addToConfig);
        scanner.setAnnotationClass(this.annotationClass);
        scanner.setMarkerInterface(this.markerInterface);
        scanner.setSqlSessionFactory(this.sqlSessionFactory);
        scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
        scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
        scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
        scanner.setResourceLoader(this.applicationContext);
        scanner.setBeanNameGenerator(this.nameGenerator);
        scanner.registerFilters();
        scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
      }

    (2)扫描package路径,获取所有定义的mapper接口的元数据(BeanDefinition):

    @Override
      public Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
    
        if (beanDefinitions.isEmpty()) {
          logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
        } else {
          processBeanDefinitions(beanDefinitions);
        }
    
        return beanDefinitions;
      }

    (3)修改元数据,将mapper类在spring容器中的Class对象替换成MapperFactoryBean:

    private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
        GenericBeanDefinition definition;
        for (BeanDefinitionHolder holder : beanDefinitions) {
          definition = (GenericBeanDefinition) holder.getBeanDefinition();
    
          if (logger.isDebugEnabled()) {
            logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() 
              + "' and '" + definition.getBeanClassName() + "' mapperInterface");
          }
    
          // the mapper interface is the original class of the bean
          // but, the actual class of the bean is MapperFactoryBean
          definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
          definition.setBeanClass(this.mapperFactoryBean.getClass());
    
          definition.getPropertyValues().add("addToConfig", this.addToConfig);
    
          boolean explicitFactoryUsed = false;
          if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
            definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
            explicitFactoryUsed = true;
          } else if (this.sqlSessionFactory != null) {
            definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
            explicitFactoryUsed = true;
          }
    
          if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
            if (explicitFactoryUsed) {
              logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
            }
            definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
            explicitFactoryUsed = true;
          } else if (this.sqlSessionTemplate != null) {
            if (explicitFactoryUsed) {
              logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
            }
            definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
            explicitFactoryUsed = true;
          }
    
          if (!explicitFactoryUsed) {
            if (logger.isDebugEnabled()) {
              logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
            }
            definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
          }
        }
      }

    (3)来看下MapperFactoryBean

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

      它集成了SqlSessionDaoSupport,也就拥有了SQLSessionTemplate,也实现了FactoryBean,来看它的getObject():

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

      在实例化Mapper对象的时候就是通过SqlSession的getMapper(MapperClass)来获取相应的Mapper代理对象。也就是当@Autowired属性注入时,会通过getObject()获取相应的实例对象。

    (4)总结

      我们平时在使用时直接在类中引入Mapper依赖,如下:

    @Service
    @Slf4j
    public class AdOrderServiceImpl implements AdOrderService {
    
        @Autowired
        private AdOrderMapper adOrderMapper;

      其实是在spring容器初始化时,扫描mapper路径(如com.coohua.garden.mapper)下所有的Mapper类,获取BeanDefinition,然后再将每个mapper的Class对象为MapperFactoryBean,而MapperFactoryBean集成了SqlSessionDaoSupport和FactoryBean,因此我们调用时就是通过JDK动态代理的方式获取到SqlSession(如果在同一事务中,SqlSession为同一个,不在同一个事务中会新创建一个,事务由spring管理),SqlSession就可以通过getMapper()获取相应的代理对象,从而调用相应的方法。

     (5)应用到的spring扩展点

      FactoryBean.getObject():可以定制化实例化bean,在实例化bean时调用该方法获取实例对象。

      InitializingBean.afterPropertiesSet():在属性注入结束后调用该方法,做一些bean初始化时的后续操作。

      ApplicationListener.onApplicationEvent():spring事件监听。

      BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry():在将bean注入到容器前修改一些bean属性,也就是修改BeadDefinition。

  • 相关阅读:
    用C#发邮件
    .Net WinForm datagridview中无法输入中文总结
    6、linux上安装kafka
    10、linux上安装hive
    8、linux上安装hbase
    4、linux 上安装mysql
    3、hadoop的分布式安装
    12、Ambari 环境搭建
    mybtais获取插入数据的主键id
    mybatis高级映射
  • 原文地址:https://www.cnblogs.com/jing-yi/p/13374346.html
Copyright © 2020-2023  润新知