软件编程
位置:首页>> 软件编程>> java编程>> Spring整合mybatis实现过程详解

Spring整合mybatis实现过程详解

作者:赫拉克利特  发布时间:2022-05-23 02:10:23 

标签:Spring,整合,mybatis

增加了用于处理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 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:

Spring整合mybatis实现过程详解

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

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

来源:https://www.cnblogs.com/mo-jian-ming/p/13288423.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com