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如下图

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

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

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

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

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 最终结构图如下:

4.7 在pom文件中添加依赖包

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

如下图:

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,具体设置如下图:

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 以上配置完成即可运行,如下图:

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进行接口测试如下:

5.15 测试结果如下图

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

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)

Spring boot Mybatis整合构建Rest服务(超细版)的更多相关文章

  1. Spring boot Mybatis 整合(完整版)

    个人开源项目 springboot+mybatis+thymeleaf+docker构建的个人站点开源项目(集成了个人主页.个人作品.个人博客) 朋友自制的springboot接口文档组件swagge ...

  2. Spring boot学习1 构建微服务:Spring boot 入门篇

    Spring boot学习1 构建微服务:Spring boot 入门篇 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框 ...

  3. Spring boot Mybatis 整合(注解版)

    之前写过一篇关于springboot 与 mybatis整合的博文,使用了一段时间spring-data-jpa,发现那种方式真的是太爽了,mybatis的xml的映射配置总觉得有点麻烦.接口定义和映 ...

  4. Spring boot Mybatis 整合

    PS: 参考博客 PS: spring boot配置mybatis和事务管理 PS: Spring boot Mybatis 整合(完整版)   这篇博客里用到了怎样 生成 mybatis 插件来写程 ...

  5. Spring Boot入门教程2-1、使用Spring Boot+MyBatis访问数据库(CURD)注解版

    一.前言 什么是MyBatis?MyBatis是目前Java平台最为流行的ORM框架https://baike.baidu.com/item/MyBatis/2824918 本篇开发环境1.操作系统: ...

  6. spring boot +mybatis 整合 连接数据库测试(从0到1)

    spring boot 整合mybatis 1.打开idea创建一个项目 2.在弹出的窗口中选择spring initializr(初始化项目),点击next 3.接下来填写group 与artifa ...

  7. 使用spring boot+mybatis+mysql 构建RESTful Service

    开发目标 开发两个RESTful Service Method Url Description GET /article/findAll POST /article/insert 主要使用到的技术 j ...

  8. Spring Boot Mybatis整合

    Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 特 ...

  9. spring boot mybatis 整合教程

    本项目使用的环境: 开发工具:Intellij IDEA 2017.1.3 springboot: 1.5.6 jdk:1.8.0_161 maven:3.3.9 额外功能 PageHelper 分页 ...

随机推荐

  1. 008Spring & JPA & Hibernate & MySQL

    01下载免安装版MySQL 02安装MySQL a)将MySQL压缩包解压到合适的位置,以C:\programmer\Tools\mysql-5.7.20-winx64路径为例: b)新建系统变量,变 ...

  2. 如何正确地在SOE中输出日志信息

    ArcGIS for Server提供完善的日志管理机制,用于日志的记录.查询和自动清除.开发人员在开发编写SOE代码时,应该采用该机制进行日志记录的输出.如果不采用该机制,输出的日志消息会写到Arc ...

  3. mybatis 关联表心得

    1,例如订单表与用户表的关联,一个订单对应一个用户,这是一对一关联: 用代码实现是这样: A(用resultType去实现的话,如下) 1,使用到继承, OrderUser extend Order{ ...

  4. 【html/css】模态框的实现

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  5. zTree 学习笔记之(一)

    zTree 学习笔记之(一) 简介 zTree 是一个依靠 jQuery 实现的多功能 “树插件”.优异的性能.灵活的配置.多种功能的组合是 zTree 最大优点. 到底有哪些具体的优点,可以参见官网 ...

  6. kernel update

    CentOS/RHEL更新包:https://rhn.redhat.com/errata/RHSA-2017-1382.html yum makecache --更新源 yum update sudo ...

  7. minimal sparse ruler problem 最少尺子刻度问题

    一个长度13的尺子,如果在1位置刻点可以量出1和12,13三种刻度.那么至少刻几个点,可以直接量出1-13所有的长度,分别刻在哪几个位置? 注:必须是直接量.即在尺子上能找出一个1-13任意的整数长度 ...

  8. 海量数据处理面试题(1) 找出两文件种包含的相同的url

    问题:给定a.b两个文件,各存放50亿个url,每个url各占64字节,内存限制是4G,让你找出a.b文件共同的url? 分析:50亿个url,每个url64字节,就是320G,显然是无法一次读入内存 ...

  9. Windows as a Service(1)—— Windows 10服务分支

    前言 作为公司的IT管理员,管理全公司Windows 10操作系统的更新一直是工作中的头疼之处.微软提供了很多方法来帮助我们管理公司的Windows 10更新,比如Windows Server Upd ...

  10. Redis集群部署-windows

    Redis集群部署-windows 前言 为了能体验一下部署Redis集群是一种怎么样的体验,所一边做一边写了这篇记录. 1.准备 从这里下载windows服务端 https://github.com ...