Springboot+ Mybatis+MySql整合构建Rest服务(涵盖增、删、改、查)

1.概要

1.1 为什么要使用Spring  boot?

  1.1.1 简单方便、配置少、整合了大多数框架

   1.1.2 适用于微服务搭建,搭建的微服务与Spring clound进行完美融合,都属于Spring家族,Spring boot+Spring clound属于品牌机,dubbo+zookeeper属于组装机,品牌机稳定性更好

1.2 使用Spring boot+Mybatis构建Restful项目详细步骤

2. 准备

2.1 使用的工具及详细版本

2.1.1 JDK       Version:1.8.0_181

2.1.2 Idea      Version:Ultimate Edition 2018.1.6

2.1.3 MySql    Version:MySql 5.7

2.1.4 Maven   Version:3.5.4

2.1.5 Mybatis-Generator   Version:1.3.5

2.1.6 Http Test Restful Webservice Idea带,没看到版本号

2.2 maven仓库地址:https://mvnrepository.com/

3. POM文件

<?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.wuji</groupId>
<artifactId>spring_boot_mybatis</artifactId>
<version>1.0-SNAPSHOT</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.1.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin> </plugins>
</build>
</project>

4. 详细开发步骤

4.1 spring_boot_mybatis模块创建:File->New->Module如下图

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

4.2 弹出窗口,选择左侧maven,点击右侧“下一步”,如下图:

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

4.3 输入,红线指的地方都设为None,点击“下一步”如下图:

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

4.4 输入,点击“完成”如下图:

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

4.5 模块创建完成,如下图:

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

4.5.1 src\main\java存放源文件

4.5.2 src\main\resources存放资源文件

4.5.3 Src\test\java存放测试文件

4.6 创建层次结构,父包为:com.wuji

4.6.1 创建mapper层:选中左侧src\main下“java”,点击File->New->Package,弹出窗口输入:com.wuji.mapper,点击“OK”

4.6.2 创建service层:同上

4.6.3 创建entity层:同上

4.6.4 创建controller层:同上

4.6.5 创建springboot启动:同上

4.6.6 最终结构图如下:

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

4.7 在pom文件中添加依赖包

4.7.1 打开https://mvnrepository.com网址,搜索:spring-boot,从列表中点击:spring-boot-starter-web,选择 2.1.1.RELEASE版本,

如下图:

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

4.7.2 同上点击:spring-boot-starter-test,选择2.1.1.RELEASE版本

4.7.3 添加mybatis-spring-boot-starter依赖,选择1.3.2版本

4.7.4 添加mysql-connector-java依赖,选择5.1.38版本

4.7.5 添加druid-spring-boot-starter依赖,选择版本1.1.10版本

4.8 配置Mybatis-Generator生成器

4.8.1 Pom文件中添加Mybatis-Generator插件依赖

4.8.2 Idea中配置:Run->Edit Configurations,具体设置如下图:

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

4.8.3 设置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="D:\MyBatisGenerator\mysql-connector-java-5.1.38.jar"/> <context id="MysqlContext" targetRuntime="MyBatis3" defaultModelType="flat"> <commentGenerator>
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true" />
</commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/daducha"
userId="root"
password="root">
</jdbcConnection> <javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!--生成PO实体类-->
<javaModelGenerator targetPackage="com.wuji.entity.po" targetProject="src/main/java">
<property name="trimStrings" value="true" />
</javaModelGenerator> <!--生成Mybatis XML Mapper Sql操作-->
<sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
</sqlMapGenerator> <!--生成Mybatis Mpper数据操作接口-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.wuji.mapper" targetProject="src/main/java">
</javaClientGenerator> <table tableName="users" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
<!--
<table tableName="%">
<generatedKey column="id" sqlStatement="Mysql"/>
</table>
-->
</context>
</generatorConfiguration>

4.8.9 将generatorConfig.xml文件放置到resources/generator/generatorConfig.xml下面

4.8.10 以上配置完成即可运行,如下图:

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

4.8.11 生成的po、mapper、mapping文件如下:

PO文件:

package com.wuji.entity.po;

public class User {
private Integer id; private String name; private Integer age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
}
}
Mapper文件:
package com.wuji.mapper;

import com.wuji.entity.po.User;

public interface UserMapper {
int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record);
}
Mapping文件(按照规则放在了资源文件夹下面):
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wuji.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.wuji.entity.po.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap>
<sql id="Base_Column_List">
id, name, age
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from users
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from users
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.wuji.entity.po.User">
insert into users (id, name, age
)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
)
</insert>
<insert id="insertSelective" parameterType="com.wuji.entity.po.User">
insert into users
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="age != null">
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.wuji.entity.po.User">
update users
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.wuji.entity.po.User">
update users
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>

4.9 application.yml文件配置(格式很严格,注意节点的缩近和对齐,有问题直接加微信回复更快

 server:
port: 8080
spring:
datasource:
name: daducha
type: com.alibaba.druid.pool.DruidDataSource
druid:
url: jdbc:mysql://127.0.0.1:3306/daducha
username: root
password: root
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
driver-class-name: com.mysql.jdbc.Driver mybatis:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.wuji.entity.po

5.10 service接口文件

 package com.wuji.service;

 import com.wuji.entity.po.User;

 public interface UserService {
int addUser(User user);
int delUserById(int id);
int updateUserById(int id,String userName);
User getUserById(int id);
}

5.11 service接口实现类

 package com.wuji.service;

 import com.wuji.entity.po.User;
import com.wuji.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class UserServiceImpl implements UserService { @Autowired
private UserMapper userMapper; public int addUser(User user) {
return userMapper.insert(user);
} public int delUserById(int id) {
return userMapper.deleteByPrimaryKey(id);
} public int updateUserById(int id,String userName) {
User user=getUserById(id);
user.setName(userName);
return userMapper.updateByPrimaryKey(user);
} public User getUserById(int id) {
return userMapper.selectByPrimaryKey(id);
}
}

5.12 controller restful风格实现

 package com.wuji.controller;
/**
* author:zhangwuji
* date:2018-12-31
* weixin:17091005779
*/
import com.wuji.entity.po.User;
import com.wuji.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController
@RequestMapping("/api/user")
public class UserController { @Autowired
private UserService userService; @RequestMapping(value = "/add",method = RequestMethod.POST)
public int addUser(User user){
return userService.addUser(user);
} @RequestMapping(value = "/get",method = RequestMethod.GET)
public User getUser(int id){
return userService.getUserById(id);
} @RequestMapping(value = "/del",method = RequestMethod.DELETE )
public int delUser(int id){return userService.delUserById(id);} @RequestMapping(value = "/update",method = RequestMethod.POST)
public int updateUser(User user){return userService.updateUserById(user);} }

5.13.spring boot 启动器文件

 package com.wuji.springboot;
/**
* author:zhangwuji
* date:2018-12-31
* weixin:17091005779
*/ import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans; @SpringBootApplication
@ComponentScan(basePackages = {"com.wuji"})
@MapperScan("com.wuji.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}

5.14 使用Test Restful Web Service进行接口测试如下:

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

5.15 测试结果如下图

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

5.16 最最终项目结构图(此结构自认为是很标准的,大家可以多发表意见)

Spring boot Mybatis整合构建Rest服务(超细版)-LMLPHP

5. 错误抛析及解决方法(可能会遇到的坑)

5.1 创建包一定要先选择src\main\java目录,右击New->Package,弹出窗口输入全路径如:com.wuji.mapper,否则会在当前选择路径下创建包,不符合Java命名约定

5.2 在启动类上添加@SpringBootApplication注解时,不能引入包;原因是:没有下载依赖

5.3 配置mybatis-generator时,working directory要设置成模块路径如:E:\JavaProjects\pring_boot_mybatis

5.4 运行mybatis-generator时出现如下错误:[ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli) on project spring_boot_mybatis: configfile E:\JavaProjects\pring_boot_mybatis\src\main\resources\generator\generatorConfig.xml does not exist ,经检查是由于generatorConfig.xml 直接在\src\main\resources下,故报找不到错误。放入正确的目录。再一次提醒Java同胞,不要任性,要遵守java命名规则约束。这些规则的使用可以标准化项目,比自己定义的结构要清晰。

5.5 [ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli) on project spring_boot_mybatis: XML Parser Error on line 46: 元素类型为 "context" 的内容必须匹配 "(property*,plugin*,commentGenerator?,(connectionFactory|jdbcConnection),javaTypeResolver?,javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+)"。 -> [Help 1] 节点要严格按照"(property*,plugin*,commentGenerator?,(connectionFactory|jdbcConnection),javaTypeResolver?,javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+)"顺序

5.6 [ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli) on project spring_boot_mybatis: Execution default-cli of goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate failed: Cannot resolve classpath entry: mysql-connector-java-5.1.38.jar -> [Help 1]是由于这个节点:<classPathEntry location="mysql-connector-java-5.1.38.jar"/>location要指定绝对路径如:<classPathEntry location="D:\MyBatisGenerator\mysql-connector-java-5.1.38.jar"/>

5.7 java.lang.IllegalStateException: Failed to load property source from location 'classpath:/application.yml'原因:application.yml首字母大写了,改为小写

5.8  org.yaml.snakeyaml.parser.ParserException: while parsing a block mapping  原因:yml文件节点没有对齐,将Mybatis节点与Spring节点对齐

5.9 No active profile set, falling back to default profiles: default这个错误是由于idea没有设置默认启动环境。具体设置如下:

5.10 Caused by: java.lang.ClassNotFoundException: org.springframework.boot.bind.RelaxedPropertyResolver这个错误是由于没有添加:<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
</parent>从而找不到RelaxedPropertyResolver这个类

5.11 Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.还是出现在yml文件节点。具体是druid:这个节点,要有层次结构。详见yml文件。

5.12 server:
  port: 8080  错误:server:标黄,提示无法解析。由于port:和8080间要加空格。

5.13 Springboot 启动文件报错,原因是@ComponentScan写成了@ComponentScans

5.14 No MyBatis mapper was found in '[com.wuji.springboot]' package. Please check your configuration.这个原因是启动器上要添加:@MapperScan("com.wuji.mapper")注解

5.15 Field userService in com.wuji.controller.UserController required a bean of type 'com.wuji.service.UserService' that could not be found.原因:说明IOC里没有创建Bean,在启动文件上手动添加:@ComponentScan(basePackages = {"com.wuji"})注解

5.16

6.总结

此文章非常详细介绍了Springboot2.0与Mybatis的整合,并且采用Rest风格作为输入和输出,项目还使用了两个很优秀的工具,一个是:Mybatis-Generator代码生成器,可以方便生成PO、Mapper接口、MapperXml映射文件,而且直接配置生成到项目指定目录下,不用做任何修改,生成的文件即可使用,同时无忌也介绍了怎样嵌入到Idea详细见上面。另一个是:Test Restful Web Service,这是个用于Rest风格接口测试工具,直接集成到Idea了,可以非常方便使用进行测试。

7.张无忌介绍:

张无忌专注Java技术10余年,产品控、代码控,拥有丰富的项目经验,主持研发了多个成功上线的大型互联网项目

热爱互联网,精通Java、J2EE,深入研究过JDK、Spring、Mybatis源码,擅长互联网高并发、高可靠架构设计。愿意

和他人分享自己对技术的理解和感悟。需要更多资源或有任何疑问可以添加张无忌微信(17091005779)

05-08 08:15