Spring boot Mybatis整合构建Rest服务(超细版)
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文件(按照规则放在了资源文件夹下面):
1 <?xml version="1.0" encoding="utf-8"?> 2 <!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 <mapper namespace="com.wuji.mapper.usermapper"> 4 <resultmap id="baseresultmap" type="com.wuji.entity.po.user"> 5 <id column="id" jdbctype="integer" property="id" /> 6 <result column="name" jdbctype="varchar" property="name" /> 7 <result column="age" jdbctype="integer" property="age" /> 8 </resultmap> 9 <sql id="base_column_list"> 10 id, name, age 11 </sql> 12 <select id="selectbyprimarykey" parametertype="java.lang.integer" resultmap="baseresultmap"> 13 select 14 <include refid="base_column_list" /> 15 from users 16 where id = #{id,jdbctype=integer} 17 </select> 18 <delete id="deletebyprimarykey" parametertype="java.lang.integer"> 19 delete from users 20 where id = #{id,jdbctype=integer} 21 </delete> 22 <insert id="insert" parametertype="com.wuji.entity.po.user"> 23 insert into users (id, name, age 24 ) 25 values (#{id,jdbctype=integer}, #{name,jdbctype=varchar}, #{age,jdbctype=integer} 26 ) 27 </insert> 28 <insert id="insertselective" parametertype="com.wuji.entity.po.user"> 29 insert into users 30 <trim prefix="(" suffix=")" suffixoverrides=","> 31 <if test="id != null"> 32 id, 33 </if> 34 <if test="name != null"> 35 name, 36 </if> 37 <if test="age != null"> 38 age, 39 </if> 40 </trim> 41 <trim prefix="values (" suffix=")" suffixoverrides=","> 42 <if test="id != null"> 43 #{id,jdbctype=integer}, 44 </if> 45 <if test="name != null"> 46 #{name,jdbctype=varchar}, 47 </if> 48 <if test="age != null"> 49 #{age,jdbctype=integer}, 50 </if> 51 </trim> 52 </insert> 53 <update id="updatebyprimarykeyselective" parametertype="com.wuji.entity.po.user"> 54 update users 55 <set> 56 <if test="name != null"> 57 name = #{name,jdbctype=varchar}, 58 </if> 59 <if test="age != null"> 60 age = #{age,jdbctype=integer}, 61 </if> 62 </set> 63 where id = #{id,jdbctype=integer} 64 </update> 65 <update id="updatebyprimarykey" parametertype="com.wuji.entity.po.user"> 66 update users 67 set name = #{name,jdbctype=varchar}, 68 age = #{age,jdbctype=integer} 69 where id = #{id,jdbctype=integer} 70 </update> 71 </mapper>
4.9 application.yml文件配置(格式很严格,注意节点的缩近和对齐,有问题直接加微信回复更快)
1 server: 2 port: 8080 3 spring: 4 datasource: 5 name: daducha 6 type: com.alibaba.druid.pool.druiddatasource 7 druid: 8 url: jdbc:mysql://127.0.0.1:3306/daducha 9 username: root 10 password: root 11 maxactive: 20 12 initialsize: 1 13 maxwait: 60000 14 minidle: 1 15 timebetweenevictionrunsmillis: 60000 16 minevictableidletimemillis: 300000 17 testwhileidle: true 18 testonborrow: false 19 testonreturn: false 20 poolpreparedstatements: true 21 maxopenpreparedstatements: 20 22 driver-class-name: com.mysql.jdbc.driver 23 24 mybatis: 25 mapper-locations: classpath:mapping/*.xml 26 type-aliases-package: com.wuji.entity.po
5.10 service接口文件
1 package com.wuji.service; 2 3 import com.wuji.entity.po.user; 4 5 public interface userservice { 6 int adduser(user user); 7 int deluserbyid(int id); 8 int updateuserbyid(int id,string username); 9 user getuserbyid(int id); 10 }
5.11 service接口实现类
1 package com.wuji.service; 2 3 import com.wuji.entity.po.user; 4 import com.wuji.mapper.usermapper; 5 import org.springframework.beans.factory.annotation.autowired; 6 import org.springframework.stereotype.service; 7 8 @service 9 public class userserviceimpl implements userservice { 10 11 @autowired 12 private usermapper usermapper; 13 14 public int adduser(user user) { 15 return usermapper.insert(user); 16 } 17 18 public int deluserbyid(int id) { 19 return usermapper.deletebyprimarykey(id); 20 } 21 22 public int updateuserbyid(int id,string username) { 23 user user=getuserbyid(id); 24 user.setname(username); 25 return usermapper.updatebyprimarykey(user); 26 } 27 28 public user getuserbyid(int id) { 29 return usermapper.selectbyprimarykey(id); 30 } 31 }
5.12 controller restful风格实现
1 package com.wuji.controller; 2 /** 3 * author:zhangwuji 4 * date:2018-12-31 5 * weixin:17091005779 6 */ 7 import com.wuji.entity.po.user; 8 import com.wuji.service.userservice; 9 import org.springframework.beans.factory.annotation.autowired; 10 import org.springframework.web.bind.annotation.requestmapping; 11 import org.springframework.web.bind.annotation.requestmethod; 12 import org.springframework.web.bind.annotation.restcontroller; 13 14 import java.util.list; 15 16 @restcontroller 17 @requestmapping("/api/user") 18 public class usercontroller { 19 20 @autowired 21 private userservice userservice; 22 23 @requestmapping(value = "/add",method = requestmethod.post) 24 public int adduser(user user){ 25 return userservice.adduser(user); 26 } 27 28 @requestmapping(value = "/get",method = requestmethod.get) 29 public user getuser(int id){ 30 return userservice.getuserbyid(id); 31 } 32 33 @requestmapping(value = "/del",method = requestmethod.delete ) 34 public int deluser(int id){return userservice.deluserbyid(id);} 35 36 @requestmapping(value = "/update",method = requestmethod.post) 37 public int updateuser(user user){return userservice.updateuserbyid(user);} 38 39 40 }
5.13.spring boot 启动器文件
1 package com.wuji.springboot; 2 /** 3 * author:zhangwuji 4 * date:2018-12-31 5 * weixin:17091005779 6 */ 7 8 import org.mybatis.spring.annotation.mapperscan; 9 import org.springframework.boot.springapplication; 10 import org.springframework.boot.autoconfigure.springbootapplication; 11 import org.springframework.context.annotation.componentscan; 12 import org.springframework.context.annotation.componentscans; 13 14 @springbootapplication 15 @componentscan(basepackages = {"com.wuji"}) 16 @mapperscan("com.wuji.mapper") 17 public class application { 18 public static void main(string[] args) { 19 springapplication.run(application.class,args); 20 } 21 }
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)
上一篇: 揭秘古代皇帝杀人的理由 真的可谓是花样百出大开眼界
下一篇: 谁在掌控云端数据 云计算七大未解之谜