项目开发中不可避免需要跟数据库打交道,作者开发的项目的中广泛使用Mybatis作为ORM框架。
本文主要讲解在Spring Boot项目中 如何整合Mybatis,基于XML方式配置下一篇中会介绍基于 注解方式的配置。
开发环境
- JDK 1.8
- Maven 3.3
- Spring Boot 1.5.8.RELEASE
- Mybatis 3.4.4
代码
首先引入spring-boot-starter-parent:
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
Mybatis依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- db-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
</dependencies>
application.yml
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: springboot.mybatis.model
type-handlers-package: springboot.mybatis.typehandler
configuration:
map-underscore-to-camel-case: true
default-fetch-size: 100
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
涉及的Mybatis Mapper类和Mapper文件 建议通过Mybatis-Generator来生产,简单、高效。
启动类App
package springboot.mybatis.xml;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* ${DESCRIPTION}
*
* @author Ricky Fung
*/
@SpringBootApplication
@MapperScan(basePackages = "com.mindflow.springboot.mybatis.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
最后,只需要在App类上增加 @MapperScan
注解即可。
源码
传送门:spring-boot-mybatis3-xml-config 查看源码