这篇文章主要为大家展示了Spring怎么整合mybatis,内容简而易懂,下面让小编带大家一起学习一下吧。

增加了用于处理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的配置

以上就是关于Spring怎么整合mybatis的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。