首页 > 其他分享 >springboot代码生成器

springboot代码生成器

时间:2022-09-18 21:46:52浏览次数:71  
标签:代码生成 springboot boot Result import org com public

一、使用springboot+mybatisplus+swagger完成如下操作

1、创建数据库表如下 channel

字段名称

中文

类型

长度

主键

外键

自增

约束

cid

栏目id

Int

 

Y

 

Y

 

cname

栏目名称

varchar

255

 

 

 

 

channel_desc

栏目描述

varchar

255

 

 

 

 

Create_time

创建时间

datetime

 

 

 

 

 

Update_time

修改时间

Datetime

 

 

 

 

 

Deleted

是否删除

Tinyint

1

 

 

 

 

2、使用mybatis-plus代码生成器,生成相关代码

3、对创建时间和更新时间做自动填充

4、对deleted做逻辑删除

5、对相应的Controller层和实体类加入swagger 说明API

6、完成Controller层中CRUD处理,并实现分页,在swagger中测试

二、使用mybatisX插件完成如下数据库表article的反向生成

字段名称

中文

类型

长度

主键

外键

自增

约束

aid

文章id

Int

 

Y

 

Y

 

Title

文章标题

varchar

255

 

 

 

 

content

文章内容

text

 

 

 

 

 

Create_time

创建时间

datetime

 

 

 

 

 

Update_time

修改时间

Datetime

 

 

 

 

 

Deleted

是否删除

Tinyint

1

 

 

 

 

Cid

关联栏目id

Int

 

 

 

 

 

 

使用

创建moduel时选择以下依赖

 

 

 

 

 

 

 

在pom.xml中加入swagger和mybatis-plus相关依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.xzit</groupId>
    <artifactId>day8_job</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>day8_job</name>
    <description>day8_job</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <!--模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--热部署驱动-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!--mysql数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!--mybatis plus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.xzit.Day8JobApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

 

测试生成器TestGenerator然后运行,自动生成出代码,再往里边儿加controller和其他配置文件

package com.xzit;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Collections;

@SpringBootTest
public class TestGenerator {
    @Test
    public void genarator(){
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8",
                "root","zengyu1234")
                .globalConfig(builder -> {
                    builder.author("IvanYu")    //设置作者
                            .enableSwagger()    //开启swagger模式
                            .fileOverride()     //覆盖已生成文件
                            .outputDir(".\\src\\main\\java");//指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.xzit")  //设置父包名
                            .moduleName("gene") //设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.xml,".\\src\\main\\resources\\mapper"));//设置mapperXml生成路径
                            //.pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("t_simple") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_") // 设置过滤表前缀
                            .entityBuilder().enableLombok()//开启lombok
                            .enableChainModel()//开启链式编程
                            .controllerBuilder().enableRestStyle();//开启RestController
                    /*因为在yml文件中配置过删除字段了,这里无需做重复配置。否则就要配置*/
                            //.logicDeletePropertyName("deleted")
                            //.logicDeleteColumnName("deleted");//配置逻辑删除处理
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}

 

复制两个config文件过来,加入分页插件和Swagger3插件

package com.xzit.gene.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //加入分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        //加入乐观锁插件
        //interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}
package com.xzit.gene.config;

import io.swagger.annotations.Api;
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;

//bean.xml applicationContext.xml
//<bean id="" class="">
@Configuration
public class Swagger3Config {
    @Bean
    public Docket apiConfig(){
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                //设置通过什么方式定位到需要生成文档的接口,
                //定位了方法上的ApiOperation
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                //接口URL路径,any表示全部的路径
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("伊万的项目")
                .description("项目描述信息")
                .contact(new Contact("伊万","http://www.baidu.com","2342342456qq.com"))
                .version("1.0")
                .build();
    }
}

 

配置Controller类

package com.xzit.gene.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.bcel.internal.generic.RET;
import com.xzit.gene.entity.Channel;
import com.xzit.gene.service.IChannelService;
import com.xzit.gene.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author IvanYu
 * @since 2022-09-18
 */
@RestController
@RequestMapping("/gene/channel")
@Api(tags = "频道管理")
public class ChannelController {
    @Resource
    private IChannelService service;

    /*这个方法使用了自定义的方法,通过xml文件配置的,自定义xml文件需要在
    * TestGenerator自动生成类里配置xml文件生成的路径,在生成的mapper.xml
    * 文件里写sql语句,在ChannelMapper.java接口以及Service层里写上对应方法
    * 此处才能调用 */
    @ApiOperation("查询全部数据")
    @GetMapping
    public Result select(){
        List<Channel> list=service.testSelect();
        return Result.success().setData("list",list);
    }

    @ApiOperation("按给定的ID查询数据")
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id){
        Channel channel = service.getById(id);
        return Result.success().setData("channel",channel);
    }

    @ApiOperation("分页查询数据")
    @GetMapping("/{current}/{size}")
    public Result selectPage(@PathVariable int current,@PathVariable int size){
        Page<Channel> page = new Page<>(current,size);
        service.page(page);
        return Result.success().setData("page",page);
    }

    @ApiOperation("保存频道")
    @PostMapping
    public Result save(@RequestBody Channel channel){
        return service.save(channel)?Result.success():Result.error();
    }

    @ApiOperation("更新频道")
    @PutMapping
    public Result update(@RequestBody Channel channel){
        return service.updateById(channel)?Result.success():Result.error();
    }

    @ApiOperation("删除频道")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        return service.removeById(id)?Result.success():Result.error();
    }
}

 

运行主类,然后访问http://localhost:8080/swagger-ui/index.html#/

测试功能均能正常运行,执行效果:

 

 

 

在Plugins里找到MybatisX插件并安装,装完以后需要重启下idea

 

标签:代码生成,springboot,boot,Result,import,org,com,public
From: https://www.cnblogs.com/zengyu1234/p/16702606.html

相关文章