Spring整合mybatis實現(xiàn)過程詳解
增加了用于處理MyBatis的兩個bean:SqlSessionFactoryBean、MapperFactoryBean
1、注冊SqlSessionFactoryBean:
(1)實現(xiàn) InitializingBean:調(diào)用其afterPropertiesSet方法(this.sqlSessionFactory = buildSqlSessionFactory())
目的就是對于sqlSessionFactory的初始化。
(2)FactoryBean:getBean方法獲取bean(= 獲取此類的getObject()返回的實例)
if (this.sqlSessionFactory == null) { afterPropertiesSet(); }return this.sqlSessionFactory;
2、注冊MapperFactoryBean:
同樣實現(xiàn)FactoryBean和InitializingBean
this.sqlSessionTemplate = createSqlSessionTemplate(sqlSessionFactory);//sqlSession作為根據(jù)接口創(chuàng)建映射器代理的接觸類一定不可以為空,設(shè)定其sqlSessionFactory屬性時完成初始化。
<bean class='org.mybatis.spring.mapper.MapperFactoryBean'> <property name='mapperInterface' value='org.cellphone.uc.repo.mapper.UserMapper'/> <property name='sqlSessionFactory' ref='sqlSessionFactory'/></bean>//接口是映射器的基礎(chǔ),sqlSession會根據(jù)接口動態(tài)創(chuàng)建相應(yīng)的代理類,所以接口必不可少。
1.0:UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
2.0:UserMapper userMapper = (UserMapper) context.getBean('userMapper');
//MyBatis在獲取映射的過程中根據(jù)配置信息為UserMapper類型動態(tài)創(chuàng)建了代理類
3、使用MapperScannerConfigurer:
讓它掃描特定的包,自動幫我們成批地創(chuàng)建映射器。不需要我們對于每個接口都注冊一個MapperFactoryBean類型的對應(yīng)的bean,在掃描的過程中通過編碼的方式動態(tài)注冊。
抽象:屏蔽掉了最原始的代碼(userMapper的創(chuàng)建)而增加了MapperScannerConfigurer的配置
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
