SpringBoot標準集成MyBatis的2種方式是怎樣的,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
創(chuàng)新互聯(lián)建站是一家集網(wǎng)站建設,林州企業(yè)網(wǎng)站建設,林州品牌網(wǎng)站建設,網(wǎng)站定制,林州網(wǎng)站建設報價,網(wǎng)絡營銷,網(wǎng)絡優(yōu)化,林州網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學習、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。
最近很多人Spring Boot中使用MyBatis時遇到的問題,大多數(shù)問題總結起來就是對MyBatis和Spring框架不熟悉的原因導致的。實際上,在Spring Boot中使用MyBatis本質就是在Spring框架中集成MyBatis,并沒有其他任何高級的東西。只不過在Spring Boot中使用時因為插件封裝的關系使得相關的配置可以更簡潔一些,但是這種封裝對于不熟悉MyBatis的人來講反而增加了理解的難度。因此,我想把如何在Spring Boot中使用MyBatis進行一個系統(tǒng)性的總結,希望能有一些參考價值。
使用任何數(shù)據(jù)庫服務器,只要是使用JDBC方式連接,都需要添加數(shù)據(jù)庫驅動,甚至還需要添加數(shù)據(jù)庫連接池依賴,如下配置以添加MySQL驅動為例進行說明。
<!-- 添加MySQL數(shù)據(jù)庫驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 添加數(shù)據(jù)庫連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${version.druid}</version>
</dependency>
在使用數(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:
當然,還可以配置數(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
這種集成方式本質上就是在Spring框架中集成MyBatis的方式,所以在非Spring Boot框架下也可以使用。
首先,添加依賴配置。
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${version.mybatis}</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>${version.mybatis.mapper}</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${version.pagehelper}</version>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${version.mybatis.spring}</version>
</dependency>
<!-- spring事務 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<!-- spring jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
其次,通過Java方式在Spring框架中注冊MyBatis的核心組件Bean,并且配置聲明式事務管理。
(1)在Spring中注冊MyBatis的核心組件Bean:SqlSessionFactory,SqlSession,以及Spring的事務管理器。另外,在構建SqlSessionFactory時還可以注冊MyBatis的xml映射器。
@Configuration
@EnableTransactionManagement
public class MyBatisSpringConfig implements TransactionManagementConfigurer {
@Autowired
private DataSource dataSource;
// 在Spring中注冊SqlSessionFactory,在這里可以設置一下參數(shù):
// 1.設置分頁參數(shù)
// 2.配置MyBatis運行時參數(shù)
// 3.注冊xml映射器
@Bean
public SqlSessionFactory sqlSessionFactory() {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// 設置數(shù)據(jù)源
sqlSessionFactoryBean.setDataSource(dataSource);
// 設置映射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ù)庫中的下劃線轉換為駝峰格式
configuration.setMapUnderscoreToCamelCase(true);
configuration.setDefaultFetchSize(100);
configuration.setDefaultStatementTimeout(30);
sqlSessionFactoryBean.setConfiguration(configuration);
// 在構建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事務管理器
@Bean(value = "transactionManager")
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
(2)注冊MyBatis接口映射器
MyBatis 3支持2種映射器:xml映射器和接口映射器,其中xml映射器可以在構建SqlSessionFactory時進行注冊。
@Configuration
@AutoConfigureAfter(MyBatisSpringConfig.class) //注意,由于MapperScannerConfigurer執(zhí)行的比較早,所以必須有該注解
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
// 設置sqlSessionFactory名
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
// 設置接口映射器基礎包名
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進行使用。
使用接口映射器
@Service
public class AccountService {
// 直接注入接口映射器Bean進行使用
@Autowired
private AccountMapper accountMapper;
public Account getAccountById(long id) {
return accountMapper.getAccountById(id);
}
}
通過插件MyBatis-Spring-Boot-Starter在Spring Boot中集成MyBatis時,可以不用再去關心原生配置方式里的細節(jié),直接使用默認配置就能實現(xiàn)最基本的功能。當然,同樣可以針對MyBatis的核心組件進行定制。所以,在這里分為2部分進行說明。第一部分說明最基礎的默認集成方式,能實現(xiàn)在Spring Boot中使用MyBatis作為ORM插件的基本功能;第二部分說明如何在Spring Boot中對MyBatis進行高級定制。在這之前,需要先添加插件MyBatis-Spring-Boot-Starter的依賴配置。
<!-- 在Spring Boot中集成MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
默認情況下,插件MyBatis-Spring-Boot-Starter將進行如下配置:
自動檢查Spring Boot的數(shù)據(jù)源配置并構建DataSource對象
通過SqlSessionFactoryBean使用數(shù)據(jù)源構建并注冊SqlSessionFactory對象
從SqlSessionFactory中創(chuàng)建并注冊一個SqlSessionTemplate實例,其實就是構建一個SqlSession對象
自動掃描接口映射器,并將這些映射器與SqlSessionTemplate實例進行關聯(lián),同時將它們注冊到Spring容器中
其實上述這些默認配置就是我們在原生集成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 注解標記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ù)源配置就可以使用了。當然,如果需要使用MyBatis更加高級的功能(如:使用xml映射器,定制MyBatis運行時參數(shù)),使用默認配置是無法實現(xiàn)的,必須在此基礎上對MyBatis進行高級的定制。
定制MyBatis運行時參數(shù)
在Spring Boot中對MyBatis進行定制主要是指在Spring Boot的配置文件中(如:application.yaml)對MyBatis運行參數(shù)進行自定義配置(使用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ù)只是一個配置示例,詳細的配置參數(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實例調用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編碼方式設置。實際上就是在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/ 。
總結起來,在Spring Boot中使用MyBatis可以使用2種方式:
使用在Spring框架中集成MyBatis的原生集成方式
使用插件MyBatis-Spring-Boot-Starter集成MyBatis
無論如何,要想在Spring Boot中靈活使用好MyBatis,最基礎的還是MyBatis和Spring框架本身。
關于SpringBoot標準集成MyBatis的2種方式是怎樣的問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關知識。
新聞標題:SpringBoot標準集成MyBatis的2種方式是怎樣的
網(wǎng)頁地址:http://bm7419.com/article10/igehgo.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供建站公司、微信小程序、網(wǎng)站策劃、網(wǎng)站制作、全網(wǎng)營銷推廣、定制網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)