Spring Boot集成MyBatis的2種方式


目錄

寫在前面

最近總是有同事和技術群的朋友提問在Spring Boot中使用MyBatis時遇到的問題,大多數問題總結起來就是對MyBatis和Spring框架不熟悉的原因導致的。實際上,在Spring Boot中使用MyBatis本質就是在Spring框架中集成MyBatis,並沒有其他任何高級的東西。只不過在Spring Boot中使用時因為插件封裝的關系使得相關的配置可以更簡潔一些,但是這種封裝對於不熟悉MyBatis的人來講反而增加了理解的難度。因此,我想把如何在Spring Boot中使用MyBatis進行一個系統性的總結,希望能有一些參考價值。

准備工作

配置數據庫驅動

使用任何數據庫服務器,只要是使用JDBC方式連接,都需要添加數據庫驅動,甚至還需要添加數據庫連接池依賴,如下配置以添加MySQL驅動為例進行說明。

<!-- 添加MySQL數據庫驅動 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 添加數據庫連接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>${version.druid}</version>
</dependency>

配置數據源

在使用數據庫之前先要在Spring Boot中配置數據源,如下所示:

spring: 
    datasource: 
        name: testDatasource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/test_springboot
        username: root
        password: 

當然,還可以配置數據庫連接池:

#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

這種集成方式本質上就是在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>

注冊MyBatis核心組件

其次,通過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,在這里可以設置一下參數:
	// 1.設置分頁參數
	// 2.配置MyBatis運行時參數
	// 3.注冊xml映射器
	@Bean
	public SqlSessionFactory sqlSessionFactory() {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		// 設置數據源
		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運行時參數
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		// 自動將數據庫中的下划線轉換為駝峰格式
		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執行的比較早,所以必須有該注解
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集成

通過插件MyBatis-Spring-Boot-Starter在Spring Boot中集成MyBatis時,可以不用再去關心原生配置方式里的細節,直接使用默認配置就能實現最基本的功能。當然,同樣可以針對MyBatis的核心組件進行定制。所以,在這里分為2部分進行說明。第一部分說明最基礎的默認集成方式,能實現在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的數據源配置並構建DataSource對象
  • 通過SqlSessionFactoryBean使用數據源構建並注冊SqlSessionFactory對象
  • 從SqlSessionFactory中創建並注冊一個SqlSessionTemplate實例,其實就是構建一個SqlSession對象
  • 自動掃描接口映射器,並將這些映射器與SqlSessionTemplate實例進行關聯,同時將它們注冊到Spring容器中

其實上述這些默認配置就是我們在原生集成MyBatis方式中做的事情,只不過在Spring Boot中通過插件MyBatis-Spring-Boot-Starter自動完成了。只要理解了這一點,就會明白如何在Spring Boot中靈活使用MyBatis組件了。
既然MyBatis的配置已經完成了,那么下一步的工作就是如何編寫和使用接口映射器。

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時非常方便,只需要添加基本的數據源配置就可以使用了。當然,如果需要使用MyBatis更加高級的功能(如:使用xml映射器,定制MyBatis運行時參數),使用默認配置是無法實現的,必須在此基礎上對MyBatis進行高級的定制。

高級定制

  • 定制MyBatis運行時參數

在Spring Boot中對MyBatis進行定制主要是指在Spring Boot的配置文件中(如:application.yaml)對MyBatis運行參數進行自定義配置(使用mybatis作為配置參數前綴):

mybatis:
    check-config-location: true                             # 是否檢測MyBatis運行參數配置文件
    config-location: classpath:/mybatis-config.xml          # 指定MyBatis運行參數配置文件位置
    mapper-locations: classpath:/mapper/**/*.xml            # 注冊XML映射器
    type-aliases-package: test.springboot.model             # 配置Java類型包名
    type-handlers-package: test.springboot.handlers         # 配置類型處理器包名
    executor-type: SIMPLE                                   # 指定執行器類型
    configuration:
        default-fetch-size: 20
        default-statement-timeout: 30

上述配置參數最終是通過mybatis-spring-boot-autoconfigure.jar加載和配置的。
另外,上述配置參數只是一個配置示例,詳細的配置參數列表請參考MyBatis配置官網:http://www.mybatis.org/mybatis-3/zh/configuration.html

  • 注冊並使用XML映射器

從定制MyBatis的運行時參數中可以看到,可以通過參數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運行時參數

MyBatis的運行時參數除了可以在Spring Boot的配置文件中指定,還可以通過Java編碼方式設置。實際上就是在Spring容器中注冊一個實現了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運行時參數
                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種方式:

  1. 使用在Spring框架中集成MyBatis的原生集成方式
  2. 使用插件MyBatis-Spring-Boot-Starter集成MyBatis

上述兩種方式都可以實現對MyBatis的定制化配置,可以根據個人喜好進行選擇。無論如何,要想在Spring Boot中靈活使用好MyBatis,最基礎的還是MyBatis和Spring框架本身。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM