在Spring项目中,两个实用的工具(生成类与映射文件、API自动生成)

news2024/9/20 12:31:59

尊贵的Spring玩家,是不允许动脑思考的,所以我们要学会复制粘贴

1.生成类与映射文件

背景:在项目编写初期,我们已经设计好了表,后面就需要根据表来撰写实体类(model)和对应的sql语句(dao和mapper)。如果一个项目中,表有很多很多,单单是花在上面的时间,估计就会占很大的一个比重。

所以,我们可以借助一些mybatis提供的一些工具来自动生成。下面介绍如何使用工具。

一共四大步:配置pom文件、编写xml配置类、双击生成、配置扫描路径和yml

(1)配置pom文件

对于pom文件,有两步。可以直接复制使用,无需修改

  • 在properties标签中加入版本号
<mybatis-generator-plugin-version>1.4.1</mybatis-generator-plugin-version>
  •  在build --> plugins标签下加入下面的配置
<!-- mybatis ⽣成器插件 -->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>${mybatis-generator-plugin-version}</version>
    <executions>
        <execution>
            <id>Generate MyBatis Artifacts</id>
            <phase>deploy</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
    <!-- 相关配置 -->
    <configuration>
        <!-- 打开⽇志 -->
        <verbose>true</verbose>
        <!-- 允许覆盖 -->
        <overwrite>true</overwrite>
        <!-- 配置⽂件路径 -->
        <configurationFile>
            src/main/resources/mybatis/generatorConfig.xml
        </configurationFile>
    </configuration>
</plugin>

位置:

(2)编写xml配置类

这一步工作量最大,需要该的地方最多,大家先复制好下面的文件,再按照步骤进行修改成自己项目中的配置

  • 第一步:创建generatorConfig.xml

在resources目录下创建一个mybatis目录,然后在mybatis目录下创建generatorConfig.xml(负责然后点击File生产即可)

问题答疑:为什么要在这个目录下,起这个名字?就是因为前面配置的pom文件已经规定了。

  • 第二步:负责下面这段代码到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>
    <!-- 驱动包路径,location中路径替换成⾃⼰本地路径 -->
    <classPathEntry location="D:\Maven\.m2\repository\mysql\mysql-connector-java\5.1.49\mysql-connector-java-5.1.49.jar"/>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!-- 禁⽤⾃动⽣成的注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <!-- 连接配置 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/forum_db?characterEncoding=utf8&amp;useSSL=false"
                        userId="root"
                        password="2003">
        </jdbcConnection>
        <javaTypeResolver>
            <!-- ⼩数统⼀转为BigDecimal -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 实体类⽣成位置 -->
        <javaModelGenerator targetPackage="org.ljy.forum6.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- mapper.xml⽣成位置 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- DAO类⽣成位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="org.ljy.forum6.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 配置⽣成表与实例, 只需要修改表名tableName, 与对应类名domainObjectName 即可-->
        <table tableName="t_article" domainObjectName="Article"
               enableSelectByExample="false"
               enableDeleteByExample="false" enableDeleteByPrimaryKey="false"
               enableCountByExample="false"
               enableUpdateByExample="false">
            <!-- 类的属性⽤数据库中的真实字段名做为属性名, 不指定这个属性会⾃动转换 _ 为驼峰命名规则-->
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="t_article_reply" domainObjectName="ArticleReply"
               enableSelectByExample="false"
               enableDeleteByExample="false" enableDeleteByPrimaryKey="false"
               enableCountByExample="false"
               enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="t_board" domainObjectName="Board"
               enableSelectByExample="false" enableDeleteByExample="false"
               enableDeleteByPrimaryKey="false" enableCountByExample="false"
               enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="t_message" domainObjectName="Message"
               enableSelectByExample="false"
               enableDeleteByExample="false" enableDeleteByPrimaryKey="false"
               enableCountByExample="false"
               enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="t_user" domainObjectName="User"
               enableSelectByExample="false" enableDeleteByExample="false"
               enableDeleteByPrimaryKey="false" enableCountByExample="false"
               enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true"/>
        </table>
    </context>
</generatorConfiguration>

先别管那么多,先复制到进去再说,下面再说修改的地方

  • 第三步:修改对应值

1)修改驱动包路径

<classPathEntry location="D:\Maven\.m2\repository\mysql\mysql-connector-java\5.1.49\mysql-connector-java-5.1.49.jar"/>

这个需要找到本地maven仓库里面存放关于mysql的jar包路径,也就是:本地存放jar的包路径(在maven学习阶段,也就是配置本地镜像时的知识点)

寻找方法:

最后加上jar包进行替换原路径即可 

2)修改数据库连接配置

位置:

修改的地方有三个:你的数据库名字,数据库用户名、数据库密码(如果是纯数字需要加上单/双引号)

3)实体类生产位置

位置:

改:框起来的修改成自己的路径,后面model包不需要改,会自己生产

4)修改dao类生成路径

位置:

这个和上面一样,修改成自己的包路径,后面的dao包会自己生产

5)注意点

下面就是一些数据表的名字,需要同步

(3)生成运行

  • 先生成一个mapper目录

  • 运行插件

修改完pom文件,记得先刷新,然后点开maven,双击运行即可生成

  • 生成的效果与后续注意

生成的三个包下

注意点:这些是系统生成的,特别是xml跟原有的dao,不要去修改它,最好的方式就是另起接口。后续也不要再双击maven,可能会生成不可控的东西。

生成完,还需要自己手动添加注解等

(4)配置路径和yml

  • 配置包扫描路径

输入以下代码:

@Configuration
@MapperScan("org.ljy.forum6.dao")
public class MybatisConfig {

}

其中:dao前面的路径需要修改成自己的

  • 配置yml
# mybatis 相关配置,单独配置,顶格写
mybatis:
 mapper-locations: classpath:mapper/**/*.xml # 指定 xxxMapper.xml的扫描路径

 至此,所有工作已完成


2.实现API自动生成

背景:在写项目的过程中,需要我们测试的接口非常的多。如果我们借助postman一个个进行输入路径和参数进行测试,那也是一个非常重的体力活。我们作为cv程序猿,怎么能允许这种事情发生呢?所以接下来跟我学习如何偷懒

下面分成三大步:配置pom文件、写配置类、配置yml文件

(1)配置pom文件

  • 在properties标签中加入版本号
<springfox-boot-starter.version>3.0.0</springfox-boot-starter.version>
  • 在dependencies标签中加入以下文件
<!-- API⽂档⽣成,基于swagger2 -->
<dependency>
 <groupId>io.springfox</groupId>
 <artifactId>springfox-boot-starter</artifactId>
 <version>${springfox-boot-starter.version}</version>
</dependency>
<!-- SpringBoot健康监控 -->
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

配置完记得进行刷新

(2)配置类

  • org.ljy.forum6包下新建SwaggerConfig.java

加入以下的代码:

import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.*;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Swagger配置类
 *
 * @Author 比特就业课
 */
// 配置类
@Configuration
// 开启Springfox-Swagger
@EnableOpenApi
public class SwaggerConfig {

    /**
     * Springfox-Swagger基本配置
     * @return
     */
    @Bean
    public Docket createApi() {
        Docket docket = new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("org.ljy.forum6.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;

    }

    // 配置API基本信息
    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("论坛系统API")
                .description("论坛系统前后端分离API测试")
                .contact(new Contact("Bit Tech", "https://edu.bitejiuyeke.com", "2742676336@qq.com"))
                .version("1.0")
                .build();
        return apiInfo;
    }

    /**
     * 解决SpringBoot 2.6.0以上与Swagger 3.0.0 不兼容的问题
     * 复制即可
     **/
    @Bean
    public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier,
                                                                         ServletEndpointsSupplier servletEndpointsSupplier,
                                                                         ControllerEndpointsSupplier controllerEndpointsSupplier,
                                                                         EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties,
                                                                         WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment,
                basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes,
                corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath),
                shouldRegisterLinksMapping, null);
    }

    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment,
                                               String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath)
                || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }

}
  • 需要修改的地方

位置1:

controller前面的包修改成自己的。一般我们都是测试controller接口,所以就这么写。

位置2:

这些信息自己配置即可,不写也是OK的

(3)配置yml文件

在Spring节点下进行配置

spring:
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER #Springfox-Swagger兼容性配置

以上就是配置的全部工作了,这只是准备功能,要生产api还得靠自己运用注解

访问的网站:

http://127.0.0.1:13145/swagger-ui/index.html

其中,端口号改成自己项目中配置的

(4)使用API注解

这里有五大注解,分别运用在不同的地方。

  • 五大注解说明

1)@API:作用在Controller上,对控制类的说明。比如Api(tags = "我是一个controller")

2)@ApiModel:作用在响应的类上,对返回响应数据的说明

3)@ApiModelProerty:作用在类的属性上,对属性的说明

4)@ApiOperation:作用在具体方法上,对API接口的说明

5)@ApiParam:作用在方法的每一个参数上,对参数的属性进行说明

其中,最常用的就是第一、四、五个,所以其他的就不演示了

  • 效果展示

首先是运用在代码上的效果:

  • 接口效果

一定复制下面的网址:http://127.0.0.1:13145/swagger-ui/index.html,并且修改端口号,最后启动项目,才能出现上面的效果。 

  • 接口使用

  • 导入postman

不仅可以直接生成接口测试,我们还能将他们导入postman中进入永久保存

第一:复制上面的网址

http://127.0.0.1:13145/swagger-ui/index.html

第二:输入下面的位置

如果页面和上述不一样,请自行搜索关于postman导入的文章。


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2148897.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【动态规划】两个数组的 dp 问题一

两个数组的 dp 问题 1.最长公共子序列2.不相交的线3.不同的子序列4.通配符匹配 点赞&#x1f44d;&#x1f44d;收藏&#x1f31f;&#x1f31f;关注&#x1f496;&#x1f496; 你的支持是对我最大的鼓励&#xff0c;我们一起努力吧!&#x1f603;&#x1f603; 1.最长公共子序…

深度学习水印网络架构学习笔记

目前学习到的一些网络架构&#xff0c;简单整理如下。 1、END框架【嵌入器-噪声层-提取器】 HiDDeN: Hiding Data With Deep Networks. ECCV, 2018.END框架&#xff0c;对噪声层的设计。用可导操作模拟JPEG压缩的过程。 2、噪声层图像增强【Noise Layer】 MBRS: Enhancing R…

设计模式之外观设计模式

一、外观设计模式概念 外观模式 (Facade) 是一种结构型设计模式&#xff0c; 为子系统中的一组接口提供一个一致的界面&#xff0c;此模式定义了一个高层接口&#xff0c;这个接口使得这一子系统更加容易使用。 外观模式为复杂子系统提供了一个简单接口&#xff0c;并不为子系统…

[Python]案例驱动最佳入门:Python数据可视化在气候研究中的应用

在全球气候问题日益受到关注的今天&#xff0c;气温变化成为了科学家、政府、公众讨论的热门话题。然而&#xff0c;全球气温究竟是如何变化的&#xff1f;我们能通过数据洞察到哪些趋势&#xff1f;本文将通过真实模拟的气温数据&#xff0c;结合Python数据分析和可视化技术&a…

鸿蒙HarmonyOS开发:一次开发,多端部署(界面级)天气应用案例

文章目录 一、布局简介二、典型布局场景三、侧边栏 SideBarContainer1、子组件2、属性3、事件 四、案例 天气应用1、UX设计2、实现分析3、主页整体实现4、具体代码 五、运行效果 一、布局简介 布局可以分为自适应布局和响应式布局&#xff0c;二者的介绍如下表所示。 名称简介…

828华为云征文|华为云Flexus X实例docker部署最新Appsmith社区版,搭建自己的低代码平台

828华为云征文&#xff5c;华为云Flexus X实例docker部署最新Appsmith社区版&#xff0c;搭建自己的低代码平台 华为云最近正在举办828 B2B企业节&#xff0c;Flexus X实例的促销力度非常大&#xff0c;特别适合那些对算力性能有高要求的小伙伴。如果你有自建MySQL、Redis、Ng…

SQL优化-MySQL Explain中出现Select tables optimized away

文章目录 前言相关解释总结 前言 今天在做SQL优化的时候&#xff0c;在使用explain执行SQL时&#xff0c;出现了以下情况&#xff1a; EXPLAIN SELECT m1.id from station m1 INNER JOIN site s ON m1.codes.stationcode where receivetime(SELECT MAX(m2.receivetime) FROM…

基于Tesseract_OCR识别

1、安装Tesseract Mac版本&#xff0c;通过Homebrew进行安装即可brew install tesseract windows版本安装 下载地址&#xff1a;https://digi.bib.uni-mannheim.de/tesseract/ 2、更换语言包 下载语言包 https://github.com/tesseract-ocr/tesseract 亦可参照这个 Tessera…

【CTF Reverse】XCTF GFSJ1101 Mine- Writeup(反编译+动态调试+Base58编码)

Mine- 运气怎么这么差&#xff1f; 原理 Base58 Base58是用于比特币&#xff08;Bitcoin&#xff09;中使用的一种独特的编码方式&#xff0c;主要用于产生Bitcoin的钱包地址。 相比Base64&#xff0c;Base58不使用数字"0"&#xff0c;字母大写"O"&…

Linux 文件权限详解与管理

文章目录 前言一、文件权限概述1. 权限表示格式2. 权限组合值 二、查看文件权限三、修改文件所有者与所属组1. 使用 chown 修改文件所有者2. 使用 chgrp 修改文件所属组3. 添加所有者 四、修改文件权限1. 符号方式2. 八进制方式 总结 前言 在 Linux 系统中&#xff0c;文件权限…

React + Vite 多环境配置

1.根目录创建文件&#xff1a; .env.dev //测试环境 .env.development //本地环境 .env.production //正式环境 .env.uat //预发布环境 注&#xff1a;变量名必须使用 VITE_API 开头 2.package.json 配置&#xff1a; --mode 设置读取制定 .env文件 &#xff0c;默认读取.en…

Windows10安装cuda11.3.0+cudnn8.5.0,以及创建conda虚拟环境(pytorch)

1、检查电脑驱动版本为561.09&#xff0c;选择cuda版本&#xff0c;下图可知cuda版本<12.6。 nvidia-smi #查看驱动版本&#xff0c;以及最大可以安装的cuda版本 2、Anaconda3-2024.06-1-Windows-x86_64.exe下载&#xff1a; 官网&#xff1a;https://www.baidu.com/link?…

研究生存指南:必备Zotero插件,让你的文献管理更轻松

在读研阶段&#xff0c;我经常面临大量文献阅读和项目研究的任务。忽略文献整理会导致后续使用时非常不便&#xff0c;查找困难且混乱。导师向我们推荐了 Zotero&#xff0c;经过亲身试用&#xff0c;我发现它非常好用&#xff01;zotero有非常多的插件&#xff0c;能够一个就满…

了解Node开发基础知识

目录 定义架构应用场景安装版本工具代码执行REPL传递参数输出全局对象 定义 Node.js 是一个基于 V8 JavaScript 引擎构建的运行时环境&#xff0c;允许你在服务器端运行 JavaScript 代码。Node.js 允许开发者使用 JavaScript 编写服务器端代码&#xff0c;实现前后端代码的统一…

安全帽识别算法、安全帽智能识别、不戴安全帽检测算法

不戴安全帽检测算法是一种基于人工智能技术&#xff0c;用于实时监测和提醒工作人员是否正确佩戴安全帽的系统。以下是对不戴安全帽检测算法的详细介绍&#xff1a; 1. 技术原理 - 数据采集与预处理&#xff1a;通过安装在施工现场或工厂车间等场所的摄像头收集图像数据&#…

HTML 盒子标签、字符实体及废弃标签介绍

目录 HTML盒子标签 div标签 span标签 字符实体 HTML注释 HTML 废弃标签介绍 关注作者微信公众号&#xff0c;开启探索更多 HTML 知识的精彩之旅。在这里&#xff0c;你将收获丰富的 HTML 专业内容&#xff0c;深入了解这一网页开发语言的奥秘&#xff0c;不断拓展你的知识…

c语言面试字符串复制

1&#xff0c;下面这个函数的打印是什么&#xff1a; #include<stdio.h> #include<string.h>int main() {char str0[5], str1[] "welcome";strcpy(str0, str1);printf("str0:%s\r\n",str0);printf("str1:%s\r\n",str1); } larkla…

【Verilog学习日常】—牛客网刷题—Verilog快速入门—VL21

根据状态转移表实现时序电路 描述 某同步时序电路转换表如下&#xff0c;请使用D触发器和必要的逻辑门实现此同步时序电路&#xff0c;用Verilog语言描述。 电路的接口如下图所示。 输入描述&#xff1a; input A , input clk , …

uniapp+renderJS+google map开发安卓版APP非小程序

背景需求 需要在uniapp中接入google地图,研究了一番,都没有找到合适的,现在说一下教程。 效果图 前期工作 这两点缺一不可,否则你啥也看不到。 1、电脑安装L-O-U梯 用于访问G-OO-G-LE的API或者创建google map key。 2、手机安装L-O-U梯 用于显示google地图。我就是手…

SpringCloud从零开始简单搭建 - JDK17

文章目录 SpringCloud Nacos从零开始简单搭建 - JDK17一、创建父项目二、创建子项目三、集成Nacos四、集成nacos配置中心 SpringCloud Nacos从零开始简单搭建 - JDK17 环境要求&#xff1a;JDK17、Spring Boot3、maven。 那么&#xff0c;如何从零开始搭建一个 SpringCloud …