zoukankan      html  css  js  c++  java
  • 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 srcmainjava存放源文件

    4.5.2 srcmain esources存放资源文件

    4.5.3 Src estjava存放测试文件

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

    4.6.1 创建mapper层:选中左侧srcmain下“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:MyBatisGeneratormysql-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 创建包一定要先选择srcmainjava目录,右击New->Package,弹出窗口输入全路径如:com.wuji.mapper,否则会在当前选择路径下创建包,不符合Java命名约定

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

    5.3 配置mybatis-generator时,working directory要设置成模块路径如:E:JavaProjectspring_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:JavaProjectspring_boot_mybatissrcmain esourcesgeneratorgeneratorConfig.xml does not exist ,经检查是由于generatorConfig.xml 直接在srcmain esources下,故报找不到错误。放入正确的目录。再一次提醒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:MyBatisGeneratormysql-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.0Mybatis的整合,并且采用Rest风格作为输入和输出,项目还使用了两个很优秀的工具,一个是:Mybatis-Generator代码生成器,可以方便生成POMapper接口、MapperXml映射文件,而且直接配置生成到项目指定目录下,不用做任何修改,生成的文件即可使用,同时无忌也介绍了怎样嵌入到Idea详细见上面。另一个是:Test Restful Web Service,这是个用于Rest风格接口测试工具,直接集成到Idea了,可以非常方便使用进行测试。

    7.张无忌介绍:

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

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

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

  • 相关阅读:
    grunt in webstorm
    10+ Best Responsive HTML5 AngularJS Templates
    响应式布局
    responsive grid
    responsive layout
    js event bubble and capturing
    Understanding Service Types
    To add private variable to this Javascript literal object
    Centering HTML elements larger than their parents
    java5 新特性
  • 原文地址:https://www.cnblogs.com/javajiuyangzhenjing/p/10202076.html
Copyright © 2011-2022 走看看