首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring Boot 整合 MyBatis 完整教程:兩種方式詳解與最佳實踐

     編輯:Java 相關知識

前言

Spring Boot 以「約定優於配置」簡化 Spring 應用開發。本文詳解 Spring Boot 整合 MyBatis 的兩種主流方式,並提供生產級配置範例。

環境準備:整合 Druid 連線池

MyBatis 需資料來源,推薦使用阿里巴巴 Druid 高效能連線池。

application.yml 配置

spring:
  datasource:
    name: test
    url: jdbc:mysql://192.168.16.137:3306/test
    username: root
    password: 
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    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

關鍵點:type: com.alibaba.druid.pool.DruidDataSource 指定連線池實現。

方式一:mybatis-spring-boot-starter(官方推薦,零配置)

Maven 依賴

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

依賴版本控制

Starter 內部版本:

  • MyBatis 3.3.0 → 可用 <mybatis.version> 覆蓋
  • MyBatis-Spring 1.2.3 → 可用 <mybatis-spring.version> 覆蓋

application.yml 配置

mybatis:
  mapperLocations: classpath:mapper/*.xml
  typeAliasesPackage: tk.mapper.model
  # 進階配置(可選)
  config: classpath:mybatis-config.xml
  typeHandlersPackage: tk.mybatis.typehandler
  checkConfigLocation: true
  executorType: SIMPLE  # SIMPLE, REUSE, BATCH

優缺點分析

優點缺點
配置極簡,開箱即用 進階客製化受限(如複雜攔截器、多 SqlSessionFactory)
版本管理統一 除錯時較難追蹤內部 Bean 建立過程
適合標準單資料源專案 多資料源、動態切換場景支援較弱

方式二:手動配置 MyBatis-Spring(完全控制)

適用於需要客製化攔截器、多資料源、動態 SQL 構建等進階場景。

Maven 依賴

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.2</version>
</dependency>

核心配置類:MyBatisConfig

@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {

    @Autowired
    DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("tk.mybatis.springboot.model");

        // 分頁攔截器配置
        PageHelper pageHelper = new PageHelper();
        Properties props = new Properties();
        props.setProperty("reasonable", "true");
        props.setProperty("supportMethodsArguments", "true");
        props.setProperty("returnPageInfo", "check");
        props.setProperty("params", "count=countSql");
        pageHelper.setProperties(props);
        bean.setPlugins(new Interceptor[]{pageHelper});

        // Mapper XML 掃描
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        
        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}

Mapper 掃描配置(關鍵:@AutoConfigureAfter)

@Configuration
@AutoConfigureAfter(MyBatisConfig.class)  // 必須!確保 sqlSessionFactory 已建立
public class MyBatisMapperScannerConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        configurer.setBasePackage("tk.mybatis.springboot.mapper");
        return configurer;
    }
}

坑點提醒:MapperScannerConfigurer 初始化極早,無 @AutoConfigureAfter 會因找不到 sqlSessionFactory 而拋異常。

分頁外掛與通用 Mapper 整合

  • 分頁外掛:如上配置 PageHelper 至 SqlSessionFactoryBean.plugins
  • 通用 Mapper:將 MapperScannerConfigurer 類別改為 tk.mybatis.spring.mapper.MapperScannerConfigurer,屬性用 Properties 配置

參考專案

完整整合範例(含分頁、通用 Mapper):GitHub 專案

總結建議

場景推薦方式
標準單資料源、快速開發、團隊 MyBatis 經驗一般 方式一:starter
需客製化攔截器、多資料源、動態 SQL、效能調優 方式二:手動配置
遷移傳統 Spring+MyBatis 專案 方式二:配置相容性更好

無論選擇哪種方式,理解 SqlSessionFactory、SqlSessionTemplate、MapperScannerConfigurer 三大核心 Bean 的建立時機與關係,是排查整合問題的關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved