示例项目地址:https://gitee.com/zhangjunqing/spring-boot/tree/master/springboot-mybatis-sample
1 整合过程
1.1 本次整合使用druid连接池,由于spring boot本身就带mybatis,故只需要引入相关依赖就行
pom.xml文件如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.springboot</groupId> <artifactId>springboot-mybatis-sample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springoot</name> <url>http://maven.apache.org</url> <!-- 使用spring boot必须有这依赖 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.7.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- 引入web 服务tomcat,web框架spring web mvc--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MYSQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- druid数据源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.26</version> </dependency> <!-- 整合mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> <!-- mybatis分页插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>3.2.3</version> </dependency> <!-- 单元测试 启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
1.2 进行启动文件 application.yml配置
server:
port: 8080
logging:
# config: classpath:logback.xml
path: D:log
#配置数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password:
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
typeAliasesPackage: com.springboot.model #实体bean包
mapperLocations: classpath:mapper/*Mapper.xml #映射文件存放地址
1.3 启动类需要添加@MapperScan 来指定要mybatis 映射接口
package com.springboot; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan("com.springboot.mapper")//mybatis的映射接口 @SpringBootApplication //注意此类的包地址应该是最大的包,这样他就可以自动扫描其下包的所有类.否则也可以(scanBasePackages={"com.springboot.controller"})指定要扫描的包 public class App { public static void main(String[] args) throws Exception { SpringApplication.run(App.class, args); } }
注:通过引入spring boot本身mybatis的支持,在启动配置文件中 ,指定数据源,mapper文件地址,模型bean地址,然后在启动类上标注要扫描的接口,就完成了简单的mybatis整合。