您的位置:首页技术文章
文章详情页

Spring整合mybatis实现过程详解

浏览:3日期:2023-08-27 09:04:16

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

1、注册SqlSessionFactoryBean:

Spring整合mybatis实现过程详解

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

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

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

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

2、注册MapperFactoryBean:

Spring整合mybatis实现过程详解

同样实现FactoryBean和InitializingBean

this.sqlSessionTemplate = createSqlSessionTemplate(sqlSessionFactory);//sqlSession作为根据接口创建映射器代理的接触类一定不可以为空,设定其sqlSessionFactory属性时完成初始化。

<bean 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:

Spring整合mybatis实现过程详解

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。

标签: Spring
相关文章: