前言
现在业界比较流行的数据操作层框架 MyBatis,下面就讲解下 Springboot 如何整合 MyBatis,这里使用的是xml配置SQL而不是用注解。主要是 SQL 和业务代码应该隔离,方便和 DBA 校对 SQL。
我的Git
https://github.com/longshanw/shopmall.git
由于我很多功能放在同一个项目里面,所以代码看起来没有那么清晰,不过将就看还是可以的。
我的项目结构
数据库准备
数据库用的是MySQL
CREATE DATABASE shopmall;
CREATE TABLE `order_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`address_detail` varchar(255) DEFAULT NULL,
`area` varchar(255) DEFAULT NULL,
`city` varchar(255) DEFAULT NULL,
`order_number` varchar(5) DEFAULT NULL,
`order_status` varchar(255) DEFAULT NULL,
`order_time` datetime DEFAULT NULL,
`province` varchar(255) DEFAULT NULL,
`receiver` varchar(255) DEFAULT NULL,
`street` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
mybatis-generator(生成mapper/xml/model)
POM.xml文件中配置:
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
编辑generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!--数据库驱动-->
<classPathEntry location="E:SoftWareapache-maven-3.5.0 epomysqlmysql-connector-java5.1.21mysql-connector-java-5.1.21.jar"/>
<context id="mysql">
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接地址账号密码-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.11.130:3306/shopmall" userId="wls" password="Wls141215!">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!--生成Model类存放位置-->
<javaModelGenerator targetPackage="com.wls.shopmall.model" targetProject="E:workspacesIdeaProjectsshopmallsrcmainjava">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--生成映射文件存放位置-->
<sqlMapGenerator targetPackage="sqlmapper" targetProject="E:workspacesIdeaProjectsshopmallsrcmain esourcesstatic">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--生成mapper类存放位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.wls.shopmall.mapper" targetProject="E:workspacesIdeaProjectsshopmallsrcmainjava">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!--生成对应表及类名-->
<table tableName="order_info" domainObjectName="MPOrderInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
运行,见下图:
pom.xml
添加必要的依赖
<?xml version="1.0" encoding="UTF-8"?>
<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.wls.shopmall</groupId>
<artifactId>shopmall</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>shopmall</name>
<description>shopmall</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- MySql驱动 -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<version>5.1.21</version>-->
</dependency>
<!--Json库的依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.43</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties(项目中yml代替)
yml配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.11.130:3306/shopmall
username: wls
password: Wls141215!
jpa:
hibernate:
ddl-auto: update
show-sql: true
mybatis:
type-aliases-package: com.wls.shopmall.model
mapper-locations: classpath:static/sqlmapper/*.xml
check-config-location: true
# config-location: classpath:mybatis/mybatis-config.xml
logging:
level:
com.imooc.repository: debug
com.imooc.service.impl: debug
com.imooc.controller: debug
com.imooc.activemq: debug
打开 application.properties 文件, 修改相应的数据源配置,比如数据源地址、账号、密码等,如下
spring.datasource.url=jdbc:mysql://
192.168.11.130:3306/shopmall?useUnicode=true&characterEncoding=utf8
spring.datasource.username=wls
spring.datasource.password=wls141215!
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.typeAliasesPackage=com.wls.shopmall.model
mybatis.mapperLocations=classpath:mapper/*.xml
注意根据自己的实现项目目录进行相应的修改。
- mybatis.typeAliasesPackage:为实体对象所在的包,跟数据库表一一对应
- mybatis.mapperLocations:mapper文件的位置
controller
需要配置dao文件,也即操作数据表的接口。
@RestController
@RequestMapping(value = "/order")
@MapperScan(value = "com.wls.shopmall.mapper")
public class OrderInfoController {
private final static Logger logger = LoggerFactory.getLogger(OrderInfoController.class);
@Autowired
private IOrderInfoService iOrderInfoService;
@GetMapping(value = "/one/{id}")
public RespUtil<Object> findOne(@PathVariable(value = "id") Integer id) throws Exception{
return RespUtil.success(iOrderInfoService.findOne(id));
}
}
运行
右键运行 Application 应用启动类的 main 函数,然后在浏览器访问即可看到数据。
localhost:8081/shopmall/order/one/7
与SpringMVC整合MyBatis的区别
SpringMVC是通过xml进行配置,通过配置DataSource、SqlSessionFactoryBean、MapperScannerConfigurer来完成MyBatis的整合。
而SpringBoot是通过application.properties配置数据源、实体bean包名、mapper文件位置和@MapperScan
注解来配置扫描的dao路径,从而实现MyBatis的整合。