SpringBoot 標(biāo)準(zhǔn)集成MyBatis的2種方式
點擊上方藍(lán)色字體,選擇“標(biāo)星公眾號”
優(yōu)質(zhì)文章,第一時間送達(dá)
? 作者?|??47號Gamer丶
來源 |? urlify.cn/UN7J3m
寫在前面
這篇文章只是標(biāo)準(zhǔn)的使用和一些概念,高級定制等。我會在另一篇博客里對mybatis實行頂級封裝,優(yōu)化簡化它,敬請期待。
最近很多人Spring Boot中使用MyBatis時遇到的問題,大多數(shù)問題總結(jié)起來就是對MyBatis和Spring框架不熟悉的原因?qū)е碌?。實際上,在Spring Boot中使用MyBatis本質(zhì)就是在Spring框架中集成MyBatis,并沒有其他任何高級的東西。只不過在Spring Boot中使用時因為插件封裝的關(guān)系使得相關(guān)的配置可以更簡潔一些,但是這種封裝對于不熟悉MyBatis的人來講反而增加了理解的難度。因此,我想把如何在Spring Boot中使用MyBatis進(jìn)行一個系統(tǒng)性的總結(jié),希望能有一些參考價值。
準(zhǔn)備工作
配置數(shù)據(jù)庫驅(qū)動
使用任何數(shù)據(jù)庫服務(wù)器,只要是使用JDBC方式連接,都需要添加數(shù)據(jù)庫驅(qū)動,甚至還需要添加數(shù)據(jù)庫連接池依賴,如下配置以添加MySQL驅(qū)動為例進(jìn)行說明。
????mysql
????mysql-connector-java
????com.alibaba
????druid
????${version.druid}
配置數(shù)據(jù)源
在使用數(shù)據(jù)庫之前先要在Spring Boot中配置數(shù)據(jù)源,如下所示:
spring:?
????datasource:?
????????name:?testDatasource
????????driver-class-name:?com.mysql.jdbc.Driver
????????url:?jdbc:mysql://127.0.0.1:3306/test_springboot
????????username:?root
????????password:
當(dāng)然,還可以配置數(shù)據(jù)庫連接池:
#datasource
spring:?
????datasource:?
????????name:?testDatasource
????????driver-class-name:?com.mysql.jdbc.Driver
????????url:?jdbc:mysql://127.0.0.1:3306/test_springboot
????????username:?root
????????password:?
????????#?使用druid連接池
????????type:?com.alibaba.druid.pool.DruidDataSource
????????filters:?stat
????????maxActive:?20
????????initialSize:?1
????????maxWait:?60000
????????minIdle:?1
????????timeBetweenEvictionRunsMillis:?60000
????????minEvictableIdleTimeMillis:?300000
????????validationQuery:?select?'x'
????????testWhileIdle:?true
????????testOnBorrow:?false
????????testOnReturn:?false
????????poolPreparedStatements:?true
????????maxOpenPreparedStatements:?20
原生集成MyBatis
這種集成方式本質(zhì)上就是在Spring框架中集成MyBatis的方式,所以在非Spring Boot框架下也可以使用。
依賴配置
首先,添加依賴配置。
????org.mybatis
????mybatis
????${version.mybatis}
????tk.mybatis
????mapper
????${version.mybatis.mapper}
????com.github.pagehelper
????pagehelper
????${version.pagehelper}
????org.mybatis
????mybatis-spring
????${version.mybatis.spring}
????org.springframework
????spring-tx
????org.springframework
????spring-jdbc
注冊MyBatis核心組件
其次,通過Java方式在Spring框架中注冊MyBatis的核心組件Bean,并且配置聲明式事務(wù)管理。
(1)在Spring中注冊MyBatis的核心組件Bean:SqlSessionFactory,SqlSession,以及Spring的事務(wù)管理器。另外,在構(gòu)建SqlSessionFactory時還可以注冊MyBatis的xml映射器。
@Configuration
@EnableTransactionManagement
public?class?MyBatisSpringConfig?implements?TransactionManagementConfigurer?{
????@Autowired
????private?DataSource?dataSource;
????
????//?在Spring中注冊SqlSessionFactory,在這里可以設(shè)置一下參數(shù):
????//?1.設(shè)置分頁參數(shù)
????//?2.配置MyBatis運行時參數(shù)
????//?3.注冊xml映射器
????@Bean
????public?SqlSessionFactory?sqlSessionFactory()?{
????????SqlSessionFactoryBean?sqlSessionFactoryBean?=?new?SqlSessionFactoryBean();
????????//?設(shè)置數(shù)據(jù)源
????????sqlSessionFactoryBean.setDataSource(dataSource);
????????//?設(shè)置映射POJO對象包名
????????//?sqlSessionFactoryBean.setTypeAliasesPackage("org.chench.test.springboot.model");
????????
????????//?分頁插件
????????/*PageHelper?pageHelper?=?new?PageHelper();
????????Properties?properties?=?new?Properties();
????????properties.setProperty("reasonable",?"true");
????????properties.setProperty("supportMethodsArguments",?"true");
????????properties.setProperty("returnPageInfo",?"check");
????????properties.setProperty("params",?"count=countSql");
????????pageHelper.setProperties(properties);*/
????????//添加插件
????????//sqlSessionFactoryBean.setPlugins(new?Interceptor[]{pageHelper});
????????
????????//?配置mybatis運行時參數(shù)
????????org.apache.ibatis.session.Configuration?configuration?=?new?org.apache.ibatis.session.Configuration();
????????//?自動將數(shù)據(jù)庫中的下劃線轉(zhuǎn)換為駝峰格式
????????configuration.setMapUnderscoreToCamelCase(true);
????????configuration.setDefaultFetchSize(100);
????????configuration.setDefaultStatementTimeout(30);
????????
????????sqlSessionFactoryBean.setConfiguration(configuration);
????????
????????//?在構(gòu)建SqlSessionFactory時注冊xml映射器
????????ResourcePatternResolver?resolver?=?new?PathMatchingResourcePatternResolver();
????????try?{
????????????sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
????????????return?sqlSessionFactoryBean.getObject();
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????????throw?new?RuntimeException(e);
????????}
????}
????
????/**
?????*?注入sqlSession對象
?????*?@param?sqlSessionFactory
?????*?@return
?????*/
????@Bean(value?=?"sqlSession")
????public?SqlSessionTemplate?sqlSessionTemplate(SqlSessionFactory?sqlSessionFactory)?{
????????return?new?SqlSessionTemplate(sqlSessionFactory);
????}
????//?Spring事務(wù)管理器
????@Bean(value?=?"transactionManager")
????@Override
????public?PlatformTransactionManager?annotationDrivenTransactionManager()?{
????????return?new?DataSourceTransactionManager(dataSource);
????}
}
(2)注冊MyBatis接口映射器
MyBatis 3支持2種映射器:xml映射器和接口映射器,其中xml映射器可以在構(gòu)建SqlSessionFactory時進(jìn)行注冊。
@Configuration
@AutoConfigureAfter(MyBatisSpringConfig.class)?//注意,由于MapperScannerConfigurer執(zhí)行的比較早,所以必須有該注解
public?class?MyBatisMapperScannerConfig?{
????@Bean
????public?MapperScannerConfigurer?mapperScannerConfigurer()?{
????????MapperScannerConfigurer?mapperScannerConfigurer?=?new?MapperScannerConfigurer();
????????//?設(shè)置sqlSessionFactory名
????????mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
????????//?設(shè)置接口映射器基礎(chǔ)包名
????????mapperScannerConfigurer.setBasePackage("org.chench.test.springboot.mapper");
????????Properties?properties?=?new?Properties();
????????//properties.setProperty("mappers",?"org.chench.test.springboot.mapper");
????????properties.setProperty("notEmpty",?"false");
????????properties.setProperty("IDENTITY",?"MYSQL");
????????mapperScannerConfigurer.setProperties(properties);
????????return?mapperScannerConfigurer;
????}
}
定義并使用映射器
MyBatis支持2種類型的映射器:XML映射器和接口映射器,在這里以定義并使用接口映射器為例。
定義接口映射器
@Repository
public?interface?AccountMapper?{
????@Select("select?*?from?account?where?id?=?#{id}")
????public?Account?getAccountById(@Param("id")?long?id);
}
注意:在這里可以使用Spring容器的注解?@Repository 聲明MyBatis的接口映射器為一個Bean組件,這樣在使用接口映射器時可以直接注入這個接口映射器Bean進(jìn)行使用。
使用接口映射器
@Service
public?class?AccountService?{
????//?直接注入接口映射器Bean進(jìn)行使用
????@Autowired
????private?AccountMapper?accountMapper;
????
????public?Account?getAccountById(long?id)?{
????????return?accountMapper.getAccountById(id);
????}
}
通過MyBatis-Spring-Boot-Starter集成
通過插件MyBatis-Spring-Boot-Starter在Spring Boot中集成MyBatis時,可以不用再去關(guān)心原生配置方式里的細(xì)節(jié),直接使用默認(rèn)配置就能實現(xiàn)最基本的功能。當(dāng)然,同樣可以針對MyBatis的核心組件進(jìn)行定制。所以,在這里分為2部分進(jìn)行說明。第一部分說明最基礎(chǔ)的默認(rèn)集成方式,能實現(xiàn)在Spring Boot中使用MyBatis作為ORM插件的基本功能;第二部分說明如何在Spring Boot中對MyBatis進(jìn)行高級定制。在這之前,需要先添加插件MyBatis-Spring-Boot-Starter的依賴配置。
????org.mybatis.spring.boot
????mybatis-spring-boot-starter
????1.3.2
默認(rèn)配置
默認(rèn)情況下,插件MyBatis-Spring-Boot-Starter將進(jìn)行如下配置:
自動檢查Spring Boot的數(shù)據(jù)源配置并構(gòu)建DataSource對象
通過SqlSessionFactoryBean使用數(shù)據(jù)源構(gòu)建并注冊SqlSessionFactory對象
從SqlSessionFactory中創(chuàng)建并注冊一個SqlSessionTemplate實例,其實就是構(gòu)建一個SqlSession對象
自動掃描接口映射器,并將這些映射器與SqlSessionTemplate實例進(jìn)行關(guān)聯(lián),同時將它們注冊到Spring容器中
其實上述這些默認(rèn)配置就是我們在原生集成MyBatis方式中做的事情,只不過在Spring Boot中通過插件MyBatis-Spring-Boot-Starter自動完成了。只要理解了這一點,就會明白如何在Spring Boot中靈活使用MyBatis組件了。既然MyBatis的配置已經(jīng)完成了,那么下一步的工作就是如何編寫和使用接口映射器。
1.定義接口映射器
@Mapper
public?interface?AccMapper?{
????@Select("select?*?from?account?where?id?=?#{id}")
????Account?getAccount(@Param("id")?long?id);
}插件MyBatis-Spring-Boot-Starter會自動搜索使用了注解?@Mapper 的接口映射器并將其注冊到Spring容器中,因此在這里不能使用?@Repository 注解標(biāo)記MyBatis的映射器接口,這與原生方式集成MyBatis有所不同。
2.使用接口映射器
@RestController
@RequestMapping("/acc")
public?class?AccController?{
????//?直接通過自動注入的方式使用接口映射器
????@Autowired
????AccMapper?accMapper;
????@GetMapping("/{id}")
????@ResponseBody
????public?Object?acc(@PathVariable("id")?long?id)?{
????????return?accMapper.getAccount(id);
????}
}
至此可以看到,在Spring Boot中通過插件MyBatis-Spring-Boot-Starter集成MyBatis時非常方便,只需要添加基本的數(shù)據(jù)源配置就可以使用了。當(dāng)然,如果需要使用MyBatis更加高級的功能(如:使用xml映射器,定制MyBatis運行時參數(shù)),使用默認(rèn)配置是無法實現(xiàn)的,必須在此基礎(chǔ)上對MyBatis進(jìn)行高級的定制。
?
高級定制
定制MyBatis運行時參數(shù)
在Spring Boot中對MyBatis進(jìn)行定制主要是指在Spring Boot的配置文件中(如:application.yaml)對MyBatis運行參數(shù)進(jìn)行自定義配置(使用mybatis作為配置參數(shù)前綴):
mybatis:
????check-config-location:?true?????????????????????????????#?是否檢測MyBatis運行參數(shù)配置文件
????config-location:?classpath:/mybatis-config.xml??????????#?指定MyBatis運行參數(shù)配置文件位置
????mapper-locations:?classpath:/mapper/**/*.xml????????????#?注冊XML映射器
????type-aliases-package:?test.springboot.model?????????????#?配置Java類型包名
????type-handlers-package:?test.springboot.handlers?????????#?配置類型處理器包名
????executor-type:?SIMPLE???????????????????????????????????#?指定執(zhí)行器類型
????configuration:
????????default-fetch-size:?20
????????default-statement-timeout:?30
上述配置參數(shù)最終是通過mybatis-spring-boot-autoconfigure.jar加載和配置的。
另外,上述配置參數(shù)只是一個配置示例,詳細(xì)的配置參數(shù)列表請參考MyBatis配置官網(wǎng):http://www.mybatis.org/mybatis-3/zh/configuration.html 。
注冊并使用XML映射器
從定制MyBatis的運行時參數(shù)中可以看到,可以通過參數(shù)mybatis.mapper-locations指定XML映射器所在位置。另外,可以直接通過插件MyBatis-Spring-Boot-Starter在Spring容器中注冊SqlSession實例調(diào)用XML映射器,如下所示:
@RestController
@RequestMapping("/acc")
public?class?AccController?{
????//?直接注入SqlSession對象
????@Autowired
????SqlSession?sqlSession;
????
????@GetMapping("/{id}")
????@ResponseBody
????public?Object?getById(@PathVariable("id")?long?id)?{
????????return?sqlSession.selectOne("test.springboot.mybatis.mapper.getAccount",?1);
????}
}
Java方式配置MyBatis運行時參數(shù)
MyBatis的運行時參數(shù)除了可以在Spring Boot的配置文件中指定,還可以通過Java編碼方式設(shè)置。實際上就是在Spring容器中注冊一個實現(xiàn)了ConfigurationCustomizer接口的Bean。
@org.springframework.context.annotation.Configuration
public?class?MyBatisConfigByJava?{
????@Bean
????ConfigurationCustomizer?mybatisConfigurationCustomizer()?{
????????return?new?ConfigurationCustomizer()?{
????????????@Override
????????????public?void?customize(org.apache.ibatis.session.Configuration?configuration)?{
????????????????//?在Spring?Boot中以Java編碼方式配置MyBatis運行時參數(shù)
????????????????configuration.setMapUnderscoreToCamelCase(true);
????????????????configuration.addMappers("org.chench.test.springboot.mapper");
????????????}
????????};
????}
}
更加高級的定制詳見:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/ 。
總結(jié)與比較

總結(jié)起來,在Spring Boot中使用MyBatis可以使用2種方式:
使用在Spring框架中集成MyBatis的原生集成方式
使用插件MyBatis-Spring-Boot-Starter集成MyBatis
上述兩種方式都可以實現(xiàn)對MyBatis的定制化配置,可以根據(jù)個人喜好進(jìn)行選擇。無論如何,要想在Spring Boot中靈活使用好MyBatis,最基礎(chǔ)的還是MyBatis和Spring框架本身。
粉絲福利:實戰(zhàn)springboot+CAS單點登錄系統(tǒng)視頻教程免費領(lǐng)取
???
?長按上方微信二維碼?2 秒 即可獲取資料
感謝點贊支持下哈?
