Spring Boot集成MyBatis的2種方式

目錄

寫在前面

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

準備工做

配置數據庫驅動

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

<!-- 添加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中配置數據源,以下所示:mysql

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

固然,還能夠配置數據庫鏈接池:git

#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框架下也可使用。github

依賴配置

首先,添加依賴配置。spring

<!-- 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映射器。sql

@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映射器和接口映射器,在這裏以定義並使用接口映射器爲例。apache

  • 定義接口映射器
@Repository
public interface AccountMapper {
	@Select("select * from account where id = #{id}")
	public Account getAccountById(@Param("id") long id);
}

注意: 在這裏可使用Spring容器的註解@Repository聲明MyBatis的接口映射器爲一個Bean組件,這樣在使用接口映射器時能夠直接注入這個接口映射器Bean進行使用。springboot

  • 使用接口映射器
@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框架自己。

相關文章
相關標籤/搜索