当前位置: 首页 > news >正文

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

尊贵的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 generatorConfigurationPUBLIC "-//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*/@Beanpublic 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 不兼容的问题* 复制即可**/@Beanpublic 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.mrgr.cn/news/30803.html

相关文章:

  • 干耳屎硬掏不出来怎么办?质量最好的可视挖耳勺推荐
  • 2024自学网络安全的三个必经阶段(含路线图)
  • linux 进程间通信之pthread(条件变量共享和互斥锁共享)
  • 【吊打面试官系列-MySQL面试题】LIKE 声明中的%和_是什么意思?
  • 大模型研发全揭秘:如何通过评估指标优化大模型的表现?
  • C++中模板的初级使用函数模板(刚刚接触模板概念的小白也能明白)
  • MySQL篇(索引)(持续更新迭代)
  • Android 将EasyPermissions进一步封装,使得动态权限申请更加简明
  • 【devops】rsync介绍和使用
  • 利用echarts 显示图片信息
  • VMware虚拟机密码忘记了怎么办
  • kafka3.8的基本操作
  • 【Spring】IocDI详解(6)
  • mysql中的json查询
  • 元数据保护者,Caesium压缩不丢重要信息
  • 自制数据库空洞率清理工具-C版-03-EasyClean-V1.3(支持南大通用数据库Gbase8a)
  • 看完大模型,我决定改变自己的大脑
  • 气膜场馆造价解析:来自气膜厂家的专业解答—轻空间
  • 天地伟业设备主动注册协议接入SVMSPro接入
  • k8s中的存储