增加了用于處理MyBatis的兩個bean:SqlSessionFactoryBean、MapperFactoryBean
1、注冊SqlSessionFactoryBean:
(1)實現 InitializingBean:調用其afterPropertiesSet方法(this.sqlSessionFactory = buildSqlSessionFactory())
目的就是對于sqlSessionFactory的初始化。
(2)FactoryBean:getBean方法獲取bean(= 獲取此類的getObject()返回的實例)
1
2
3
4
|
if (this.sqlSessionFactory == null) { afterPropertiesSet(); } return this.sqlSessionFactory; |
2、注冊MapperFactoryBean:
同樣實現FactoryBean和InitializingBean
1
2
3
|
this.sqlSessionTemplate = createSqlSessionTemplate(sqlSessionFactory); //sqlSession 作為根據接口創建映射器代理的接觸類一定不可以為空, 設定其sqlSessionFactory屬性時完成初始化。 |
1
2
3
4
|
< 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的配置
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/mo-jian-ming/p/13288423.html