【Java开发Spring优雅编程系列5】基于Spring Boot + Mybatis +Swagger接口开发

一、概述

在平时的开发工作中,可能很多时间都是在编写一些业务代码,实现CRUD的功能,这里主要面向基础开发的小伙伴,介绍如何使用Spring Boot、Mybatis开发,通过介绍如何使用EasyCode生成DAO层、Entity代码,集成使用Swagger生成接口文档。通过这节内容可以使小伙伴们快速上手,完成功能开发。

二、数据库建表
mysql 复制代码
-- `zhc-java`.`user` definition

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键Id',
  `name` varchar(100) DEFAULT NULL COMMENT '用户姓名',
  `age` int(3) DEFAULT NULL COMMENT '年龄',
  `mobile` varchar(20) DEFAULT NULL COMMENT '用户手机号',
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
  `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
  `gender` tinyint(4) DEFAULT NULL COMMENT '性别,1男 2女 0 未知',
  `status` tinyint(4) DEFAULT NULL COMMENT '状态,0 禁用 1启用',
  `is_deleted` bit(1) DEFAULT b'0' COMMENT '是否删除',
  `source` tinyint(4) DEFAULT NULL COMMENT '用户来源',
  `id_card` varchar(32) DEFAULT NULL COMMENT '身份证号',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='用户信息表';
二、EasyCode插件使用
插件下载

在Idea 开发工具,点击菜单-File-Setting-Plugins,搜索EasyCode,下载安装插件,重启idea生效。

配置DataBase

在Idea开发工具右侧,点击DataBase旁边加号+,新增数据源,选择数据库类型,这里是Mysql,按照如下图所示,填写数据库配置信息。

代码生成

鼠标右键选择需要生成代码的表,点击EasyCode菜单,再点击Generate Code弹出如下图所示:

填写对应配置项,确认之后点击OK就完成基础代码生成。

三、Mybatis 使用介绍
依赖导入
xml 复制代码
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3.1</version>
</dependency>

由于Mybatis-Plus对Mybatis具有较好的兼容性,因此这里Maven直接引入Mybatis-Plus对应starter。

主要标签

1、select标签 属性介绍: (1)id :唯一的标识符. (2)parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User或user (3)resultType :语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型,而不是集合本身(resultType 与resultMap 不能并用)

xml 复制代码
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
        select * from student where id=#{id}
</select>

2、insert标签

属性介绍: (1)id :唯一的标识符 (2)parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User

xml 复制代码
<insert id="insertAgent" parameterType="Object">
    INSERT  INTO t_node_agent (host_name, os_type, created_date)
    VALUES (#{hostName}, #{osType}, #{createdDate})
</insert>

3、delete标签 属性与insert标签类似

xml 复制代码
<delete id="deleteByPrimaryKey" parameterType="Object">
        delete from student where id=#{id}
</delete>

4、update标签 属性与insert标签类似

xml 复制代码
<!--通过主键修改数据-->
    <update id="update">
        update user
        <set>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
        </set>
        where id = #{id}
    </update>

5、resultMap标签 基本作用:建立SQL查询结果字段与实体属性的映射关系信息,查询的结果集转换为java对象,方便进一步操作,将结果集中的列与java对象中的属性对应起来并将值填充进去; 标签说明: 主标签 (1)id:该resultMap的标志 (2)type:返回值的类名,此例中返回EStudnet类 子标签: (1)id:用于设置主键字段与领域模型属性的映射关系,此处主键为ID,对应id。 (2)result:用于设置普通字段与领域模型属性的映射关系 6、if标签(重要) if标签通常用于WHERE语句中,通过判断参数值来决定是否使用某个查询条件, 他也经常用于UPDATE语句中判断是否更新某一个字段,还可以在INSERT语句中用来判断是否插入某个字段的值

xml 复制代码
<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST      
    <if test="studentName!=null and studentName!='' ">     
        WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
    </if>     
</select>  

7、foreach标签 foreach标签主要用于构建in条件,他可以在sql中对集合进行迭代。如下:

xml 复制代码
<delete id="deleteBatch"> 
    delete from user where id in
    <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
      #{id}
    </foreach>
</delete>

(1)collection :collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合,我在上面传的参数为数组,所以值为array item : 表示在迭代过程中每一个元素的别名 (2)index :表示在迭代过程中每次迭代到的位置(下标) (3)open :前缀 (4)close :后缀 (5)separator :分隔符,表示迭代时每个元素之间以什么分隔 8、choose 标签的使用 有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件是否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行 otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。

xml 复制代码
<select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST      
    <where>     
        <choose>     
            <when test="studentName!=null and studentName!='' ">     
                    ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
            </when>     
            <when test="studentSex!= null and studentSex!= '' ">     
                    AND ST.STUDENT_SEX = #{studentSex}      
            </when>     
            <when test="studentBirthday!=null">     
                AND ST.STUDENT_BIRTHDAY = #{studentBirthday}      
            </when>     
            <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">     
                AND ST.CLASS_ID = #{classEntity.classID}      
            </when>     
            <otherwise>     
            </otherwise>     
        </choose>     
    </where>     
</select>  

9、include标签,用于sql之间互相引用。

四、Swagger使用集成
依赖导入
xml 复制代码
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
    </dependency>
    <dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.5.14</version>
    </dependency>
    <dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>2.0.2</version>
</dependency>
主要注解介绍

1、@Api @Api注解用于描述API接口的基本信息,包括接口名称、描述、作者等。具体使用方法如下:

less 复制代码
@Api(value = "UserController", description = "用户管理接口", tags = {"用户管理"})
@RestController
@RequestMapping("/user")
public class UserController {
    // ...
}

value:接口名称,必填项。 description:接口描述,非必填项。 tags:接口标签,用于对接口进行分类,非必填项。 2、@ApiOperation @ApiOperation注解用于描述API接口的操作方法,包括HTTP请求方法、接口路径、接口说明等。具体使用方法如下:

less 复制代码
@ApiOperation(value = "获取用户列表", notes = "获取所有用户列表")
@GetMapping("/list")
public List<User> getUserList() {
    // ...
}

value:接口名称,必填项。 notes:接口说明,非必填项。 httpMethod:HTTP请求方法,非必填项,默认为GET。 response:接口返回结果类型,非必填项。 responseContainer:接口返回结果容器类型,非必填项。 3、@ApiModel @ApiModel注解用于描述API接口的返回结果类型,包括返回结果的数据结构、返回结果的说明等。具体使用方法如下: @ApiModel(value = "User", description = "用户信息")

kotlin 复制代码
public class User {
    @ApiModelProperty(value = "用户ID")
    private Long id;
    
    @ApiModelProperty(value = "用户名")
    private String username;
    
    @ApiModelProperty(value = "用户密码")
    private String password;
    
    // ...
}

4、@ApiModelProperty @ApiModelProperty注解用于描述API接口返回结果的属性信息,包括属性名称、属性类型、属性说明等。具体使用方法如下:

kotlin 复制代码
@ApiModel(value = "User", description = "用户信息")
public class User {
    @ApiModelProperty(value = "用户ID")
    private Long id;
    
    @ApiModelProperty(value = "用户名")
    private String username;
    
    @ApiModelProperty(value = "用户密码")
    private String password;
    
    // ...
}

value:属性说明,必填项。 name:属性名称,非必填项,默认为属性的变量名。 dataType:属性类型,非必填项,默认为属性的类型。 required:属性是否必填,非必填项,默认为false。 example:属性示例值,非必填项。

编写Swagger配置类
typescript 复制代码
package com.zhc.config.swagger;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger 配置
 * @author zhouhengchao
 * @since 2023-11-30 10:29:00
 */
@Configuration
@EnableKnife4j
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 是否启用Swagger
                .enable(true)
                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                .apiInfo(apiInfo())
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api,用这种方式更灵活
//                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .apis(RequestHandlerSelectors.basePackage("com.zhc.controller.spring.mybatis"))
                // 扫描指定包中的swagger注解
                // .apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.tool.swagger"))
                // 扫描所有 .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
        /* 设置安全模式,swagger可以设置访问token */
//                .securitySchemes(securitySchemes())
//                .securityContexts(securityContexts());
    }


    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                // 设置标题
                .title("标题:ZHC开源项目_接口文档")
                // 描述
                .description("Zhc-Java接口文档")
                // 作者信息
                .contact(new Contact("zhc", "https://space.bilibili.com/414132161", "zhc@qq.com"))
                // 版本
                .version("版本号:V1.0")
                .build();
    }
}

详细内容请参考:github.com/zhcyixin/zh...

相关推荐
Satan7121 分钟前
【Java】全面理解Java8特性
java·开发语言
至简行远3 分钟前
路由器接口配置DHCP实验简述
java·服务器·网络·数据结构·python·算法·智能路由器
c1tenj24 分钟前
SpringCloud Feign 以及 一个标准的微服务的制作
java·spring cloud·微服务
小郝同学(恩师白云)18 分钟前
SpringMVC后续4
java·服务器·前端
March€22 分钟前
基于mockito做单元测试
java·单元测试·log4j
秋月的私语30 分钟前
c# 线程等待变量的值符合条件
java·jvm·c#
Stringzhua30 分钟前
SpringBean的生命周期
java·spring
武子康30 分钟前
大数据-141 - ClickHouse 集群 副本和分片 Zk 的配置 Replicated MergeTree原理详解
java·大数据·clickhouse·flink·spark·scala
人生导师yxc32 分钟前
Java面向对象编程
java·开发语言
一只雪球球35 分钟前
【练习16】求最小公倍数
java·开发语言