1. 程式人生 > 程式設計 >Spring整合mybatis實現過程詳解

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的配置

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。