Springboot整合MyBatisPlus swagger测试

简介: Springboot整合MyBatisPlus swagger测试

介绍:

本篇我们介绍一下Springboot整合MyBatisPlus后台相对比较完整的代码,以swager来进行测试。

主要依赖

   <!--mybatis-plus-->

   <dependency>

     <groupId>com.baomidou</groupId>

     <artifactId>mybatis-plus-boot-starter</artifactId>

     <version>3.3.1</version>

   </dependency>

   <!--freemarker-->

   <dependency>

     <groupId>org.freemarker</groupId>

     <artifactId>freemarker</artifactId>

     <version>2.3.30</version>

   </dependency>

   <!--代码生成器-->

   <dependency>

     <groupId>com.baomidou</groupId>

     <artifactId>mybatis-plus-generator</artifactId>

     <version>3.4.1</version>

   </dependency>

   <!--swagger-->

   <dependency>

     <groupId>io.springfox</groupId>

     <artifactId>springfox-swagger2</artifactId>

     <version>2.9.2</version>

   </dependency>

   <dependency>

     <groupId>io.springfox</groupId>

     <artifactId>springfox-swagger-ui</artifactId>

     <version>2.9.2</version>

   </dependency>

代码生成器代码

public class CodeGenerator {

   /**

    * <p>

    * 读取控制台内容

    * </p>

    */

   public static String scanner(String tip) {

       Scanner scanner = new Scanner(System.in);

       StringBuilder help = new StringBuilder();

       help.append("请输入" + tip + ":");

       System.out.println(help.toString());

       if (scanner.hasNext()) {

           String ipt = scanner.next();

           if (StringUtils.isNotBlank(ipt)) {

               return ipt;

           }

       }

       throw new MybatisPlusException("请输入正确的" + tip + "!");

   }

   public static void main(String[] args) {

       // 代码生成器

       AutoGenerator mpg = new AutoGenerator();

       // 全局配置

       GlobalConfig gc = new GlobalConfig();

       String projectPath = System.getProperty("user.dir");

       gc.setOutputDir(projectPath + "/src/main/java");

       gc.setAuthor("elite");

       gc.setOpen(false);

       // gc.setSwagger2(true); 实体属性 Swagger2 注解

       mpg.setGlobalConfig(gc);

       // 数据源配置

       DataSourceConfig dsc = new DataSourceConfig();

       dsc.setUrl("jdbc:mysql://数据库ip:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");

       // dsc.setSchemaName("public");

       dsc.setDriverName("com.mysql.jdbc.Driver");

       dsc.setUsername("root");

       dsc.setPassword("123456");

       mpg.setDataSource(dsc);

       // 包配置

       PackageConfig pc = new PackageConfig();

       pc.setModuleName(scanner("模块名"));

       pc.setParent("com.elite");

       mpg.setPackageInfo(pc);

       // 自定义配置

       InjectionConfig cfg = new InjectionConfig() {

           @Override

           public void initMap() {

               // to do nothing

           }

       };

       // 如果模板引擎是 freemarker

       String templatePath = "/templates/mapper.xml.ftl";

       // 如果模板引擎是 velocity

       // String templatePath = "/templates/mapper.xml.vm";

       // 自定义输出配置

       List<FileOutConfig> focList = new ArrayList<>();

       // 自定义配置会被优先输出

       focList.add(new FileOutConfig(templatePath) {

           @Override

           public String outputFile(TableInfo tableInfo) {

               // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!

               return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()

                       + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;

           }

       });

       /*

       cfg.setFileCreate(new IFileCreate() {

           @Override

           public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {

               // 判断自定义文件夹是否需要创建

               checkDir("调用默认方法创建的目录,自定义目录用");

               if (fileType == FileType.MAPPER) {

                   // 已经生成 mapper 文件判断存在,不想重新生成返回 false

                   return !new File(filePath).exists();

               }

               // 允许生成模板文件

               return true;

           }

       });

       */

       cfg.setFileOutConfigList(focList);

       mpg.setCfg(cfg);

       // 配置模板

       TemplateConfig templateConfig = new TemplateConfig();

       // 配置自定义输出模板

       //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别

       // templateConfig.setEntity("templates/entity2.java");

       // templateConfig.setService();

       // templateConfig.setController();

       templateConfig.setXml(null);

       mpg.setTemplate(templateConfig);

       // 策略配置

       StrategyConfig strategy = new StrategyConfig();

       strategy.setNaming(NamingStrategy.underline_to_camel);

       strategy.setColumnNaming(NamingStrategy.underline_to_camel);

       //strategy.setSuperEntityClass("BaseEntity");

       strategy.setEntityLombokModel(true);

       strategy.setRestControllerStyle(true);

       // 公共父类

       //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");

       // 写于父类中的公共字段

       //strategy.setSuperEntityColumns("id");

       //strategy.setSuperEntityColumns("id");

       //strategy.setSuperEntityColumns("id");

       //strategy.setSuperEntityColumns("id");

       strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));

       strategy.setControllerMappingHyphenStyle(true);

       strategy.setTablePrefix(pc.getModuleName() + "_");

       mpg.setStrategy(strategy);

       mpg.setTemplateEngine(new FreemarkerTemplateEngine());

       mpg.execute();

   }

}

执行代码生成器,系统会自动生成controller,service以及mapper。mybatisplus提供了部分封装好的方法。

service层

/**

* <p>

* 订单表 服务类

* </p>

*

* @author elite

* @since 2022-08-22

*/

public interface IOrderService extends IService<Order> {

}

/**

* <p>

* 订单表 服务实现类

* </p>

*

* @author elite

* @since 2022-08-22

*/

@Service

public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

}

mapper

/**

* <p>

* 订单表 Mapper 接口

* </p>

*

* @author elite

* @since 2022-08-22

*/

public interface OrderMapper extends BaseMapper<Order> {

}

controller

/**

* <p>

* 订单表 前端控制器

* </p>

*

* @author elite

* @since 2022-08-22

*/

@RestController

@RequestMapping("/springboot/order")

@Api(tags = "订单接口")

public class OrderController {

   @Autowired

   IOrderService orderService;

   /**

    * 获取订单列表

    */

   @ApiOperation(value = "获取订单列表")

   @GetMapping("/getOrderList")

   public R getOrderList(){

       List<Order> orderList = orderService.list();

       return R.ok(orderList);

   }

   /**

    * 分页获取订单列表

    */

   @ApiOperation(value = "分页获取订单列表")

   @PostMapping("/getOrderListByPage/{currentPage}/{PageSize}")

   public R getOrderListPage(@PathVariable("currentPage")Integer currentPage,

                             @PathVariable("PageSize") Integer PageSize,

                             @RequestBody Order order){

       QueryWrapper<Order> queryWrapper = new QueryWrapper<>();

       IPage<Order> page = new Page<>();

       page.setCurrent(currentPage);

       page.setSize(PageSize);

       //订单ID

       //queryWrapper.eq("order_id",order.getOrderId());

      queryWrapper.eq("order_no",order.getOrderNo());

       IPage<Order> Orders = orderService.page(page, queryWrapper);

       return R.ok(Orders);

   }

   /**

    * 通过订单ID获取订单信息

    */

   @ApiOperation(value = "通过订单ID获取订单信息")

   @GetMapping("/getOrderById/{order_id}")

   public R getOrderById(@PathVariable("order_id") Integer order_id){

       Order order = orderService.getById(order_id);

       return R.ok(order);

   }

   /**

    * 保存订单信息

    */

   @ApiOperation(value = "保存订单信息")

   @PostMapping("/saveOrder")

   public R saveOrder(@RequestBody Order order){

       boolean save = orderService.save(order);

       if (save){

           return R.ok(null);

       }

       return R.fail();

   }

   /**

    * 更新订单信息

    */

   @ApiOperation(value = "更新订单信息")

   @PutMapping("/updateOrder")

   public R updateOrder(@RequestBody Order order){

       Wrapper<Order> updateWrapper = new UpdateWrapper<>();

       boolean success = orderService.update(updateWrapper);

       if (success){

           return R.ok(null);

       }

       return R.fail();

   }

   /**

    * 删除订单信息

    */

   @ApiOperation(value = "删除订单信息")

   @DeleteMapping("/delOrderById")

   public R delOrderById(@PathVariable("order_id") Integer order_id){

       boolean success = orderService.removeById(order_id);

       if (success){

           return R.ok(null);

       }

       return R.fail();

   }

}

实体类Order

**

* <p>

* 订单表

* </p>

*

* @author elite

* @since 2022-08-22

*/

@ApiModel("订单表")

@Data

@EqualsAndHashCode(callSuper = false)

@TableName("`order`")

public class Order implements Serializable {

   private static final long serialVersionUID = 1L;

   /**

    * 订单ID

    */

   @ApiModelProperty(value = "订单ID")

   @TableId(value = "order_id", type = IdType.AUTO)

   private Integer orderId;

   /**

    * 订单号

    */

   @TableField(value = "order_no")

   private Integer orderNo;

   /**

    * 产品id

    */

   @TableField(value = "product_id")

   private Integer productId;

   /**

    * 用户ID

    */

   @TableField(value = "user_id")

   private Integer userId;

   /**

    * 订单产品数量

    */

   @TableField(value = "order_num")

   private Integer orderNum;

   /**

    * 订单金额

    */

   @TableField(value = "order_amt")

   private BigDecimal orderAmt;

   /**

    * 订单状态

    */

   @TableField(value = "order_status")

   private String orderStatus;

   /**

    * 支付状态

    */

   @TableField(value = "pay_status")

   private String payStatus;

   /**

    * 创建时间

    */

   @TableField(value = "create_time")

   private LocalDateTime createTime;

   /**

    * 更新时间

    */

   @TableField(value = "update_time")

   private LocalDateTime updateTime;

   /**

    * 创建人

    */

   @TableField(value = "create_user")

   private String createUser;

   /**

    * 更新人

    */

   @TableField(value = "update_user")

   private String updateUser;

}

swagger


API Developmentfor Everyone


Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset. Find out how Swagger can help you design and document your APIs at scale.


制作API接口文档非常方便


常用的注解:


@Api:标注在一个类上


@ApiOperation :在方法上


@ApiModel :用于标注一个实体类


@ApiModelProperty:标注属性


接口文档访问地址:


http://ip地址:port/swagger-ui.html#/


分页测试

Response body

Download

{

 "code": 200,

 "msg": "成功",

 "data": {

   "records": [

     {

       "orderId": 3,

       "orderNo": 2,

       "productId": 2,

       "userId": 1,

       "orderNum": 2,

       "orderAmt": 20,

       "orderStatus": "取消下单",

       "payStatus": "未支付",

       "createTime": "2022-08-21T11:20:29",

       "updateTime": "2022-08-21T11:20:29",

       "createUser": "annotation",

       "updateUser": "annotation"

     }

   ],

   "total": 1,

   "size": 2,

   "current": 1,

   "orders": [],

   "optimizeCountSql": true,

   "hitCount": false,

   "countId": null,

   "maxLimit": null,

   "searchCount": true,

   "pages": 1

 }

}


目录
打赏
0
0
0
0
35
分享
相关文章
必学!Spring Boot 单元测试、Mock 与 TestContainer 的高效使用技巧
【10月更文挑战第18天】 在现代软件开发中,单元测试是保证代码质量的重要手段。Spring Boot提供了强大的测试支持,使得编写和运行测试变得更加简单和高效。本文将深入探讨Spring Boot的单元测试、Mock技术以及TestContainer的高效使用技巧,帮助开发者提升测试效率和代码质量。
534 2
基于SpringBoot+Vue实现的大学生体质测试管理系统设计与实现(系统源码+文档+数据库+部署)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
55 2
Spring Boot 如何测试打包部署
本文介绍了 Spring Boot 项目的开发、调试、打包及投产上线的全流程。主要内容包括: 1. **单元测试**:通过添加 `spring-boot-starter-test` 包,使用 `@RunWith(SpringRunner.class)` 和 `@SpringBootTest` 注解进行测试类开发。 2. **集成测试**:支持热部署,通过添加 `spring-boot-devtools` 实现代码修改后自动重启。 3. **投产上线**:提供两种部署方案,一是打包成 jar 包直接运行,二是打包成 war 包部署到 Tomcat 服务器。
53 10
springboot之SpringBoot单元测试
本文介绍了Spring和Spring Boot项目的单元测试方法,包括使用`@RunWith(SpringJUnit4ClassRunner.class)`、`@WebAppConfiguration`等注解配置测试环境,利用`MockMvc`进行HTTP请求模拟测试,以及如何结合Spring Security进行安全相关的单元测试。Spring Boot中则推荐使用`@SpringBootTest`注解简化测试配置。
168 4
详解Swagger:Spring Boot中的API文档生成与测试工具
详解Swagger:Spring Boot中的API文档生成与测试工具
142 4
使用Spring Boot编写测试用例:实践与最佳实践
使用Spring Boot编写测试用例:实践与最佳实践
191 0
接口测试新选择:Postman替代方案全解析
在软件开发中,接口测试工具至关重要。Postman长期占据主导地位,但随着国产工具的崛起,越来越多开发者转向更适合中国市场的替代方案——Apifox。它不仅支持中英文切换、完全免费不限人数,还具备强大的可视化操作、自动生成文档和API调试功能,极大简化了开发流程。
大前端之前端开发接口测试工具postman的使用方法-简单get接口请求测试的使用方法-简单教学一看就会-以实际例子来说明-优雅草卓伊凡
大前端之前端开发接口测试工具postman的使用方法-简单get接口请求测试的使用方法-简单教学一看就会-以实际例子来说明-优雅草卓伊凡
94 10
大前端之前端开发接口测试工具postman的使用方法-简单get接口请求测试的使用方法-简单教学一看就会-以实际例子来说明-优雅草卓伊凡
以项目登录接口为例-大前端之开发postman请求接口带token的请求测试-前端开发必学之一-如果要学会联调接口而不是纯写静态前端页面-这个是必学-本文以优雅草蜻蜓Q系统API为实践来演示我们如何带token请求接口-优雅草卓伊凡
以项目登录接口为例-大前端之开发postman请求接口带token的请求测试-前端开发必学之一-如果要学会联调接口而不是纯写静态前端页面-这个是必学-本文以优雅草蜻蜓Q系统API为实践来演示我们如何带token请求接口-优雅草卓伊凡
56 5
以项目登录接口为例-大前端之开发postman请求接口带token的请求测试-前端开发必学之一-如果要学会联调接口而不是纯写静态前端页面-这个是必学-本文以优雅草蜻蜓Q系统API为实践来演示我们如何带token请求接口-优雅草卓伊凡
Python测试淘宝店铺所有商品接口的详细指南
本文详细介绍如何使用Python测试淘宝店铺商品接口,涵盖环境搭建、API接入、签名生成、请求发送、数据解析与存储、异常处理等步骤。通过具体代码示例,帮助开发者轻松获取和分析淘宝店铺商品数据,适用于电商运营、市场分析等场景。遵守法规、注意调用频率限制及数据安全,确保应用的稳定性和合法性。
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等