Spring整合mybatis Spring整合mybatis实现过程详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring整合mybatis Spring整合mybatis实现过程详解

赫拉克利特   2021-01-29 我要评论

增加了用于处理MyBatis的两个bean:SqlSessionFactoryBean、MapperFactoryBean

1、注册SqlSessionFactoryBean:

(1)实现 InitializingBean:调用其afterPropertiesSet方法(this.sqlSessionFactory = buildSqlSessionFactory())

目的就是对于sqlSessionFactory的初始化。

(2)FactoryBean:getBean方法获取bean(= 获取此类的getObject()返回的实例)

if (this.sqlSessionFactory == null) {
    afterPropertiesSet();
  }
return this.sqlSessionFactory;

2、注册MapperFactoryBean:

同样实现FactoryBean和InitializingBean

this.sqlSessionTemplate = createSqlSessionTemplate(sqlSessionFactory);
//sqlSession作为根据接口创建映射器代理的接触类一定不可以为空,
设定其sqlSessionFactory属性时完成初始化。
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="org.cellphone.uc.repo.mapper.UserMapper"/>
  <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>//接口是映射器的基础,sqlSession会根据接口动态创建相应的代理类,所以接口必不可少。

1.0:UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

2.0:UserMapper userMapper = (UserMapper) context.getBean("userMapper");

//MyBatis在获取映射的过程中根据配置信息为UserMapper类型动态创建了代理类

3、使用MapperScannerConfigurer:

让它扫描特定的包,自动帮我们成批地创建映射器。不需要我们对于每个接口都注册一个MapperFactoryBean类型的对应的bean,在扫描的过程中通过编码的方式动态注册。

抽象:屏蔽掉了最原始的代码(userMapper的创建)而增加了MapperScannerConfigurer的配置

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们