【JAVA】使用EasyCode插件来根据表模型自动生成CURD

这篇博客介绍了如何在IDEA中通过EasyCode插件自动生成MybatisPlus的Entity、DAO、Service、ServiceImpl和Controller代码,并配置了Swagger注解以生成API文档。同时,展示了配置MybatisPlus分页插件、Swagger配置和添加必要的依赖。此外,还提供了模板示例和启动项目的步骤。
摘要由CSDN通过智能技术生成

通过IDEA插件库安装EasyCode插件
在这里插入图片描述
连接数据库
请添加图片描述
在Settings中配置字段类型映射 模板等
在这里插入图片描述
这边用的是MybaitisPlus
entity

##导入宏定义
$!define

##保存文件(宏定义)
#save("/entity", ".java")

##包路径(宏定义)
#setPackageSuffix("entity")

##自动导入包(全局变量)
$!autoImport
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serializable;

##表注释(宏定义)
#tableComment("表实体类")
@EqualsAndHashCode(callSuper = true)
@Data
@ApiModel("$tableInfo.comment")
public class $!{tableInfo.name} extends Model<$!{tableInfo.name}> implements Serializable {
    private static final long serialVersionUID = $!tool.serial();
#foreach($column in $tableInfo.pkColumn)
    #if(${column.comment})/**
    * ${column.comment}
    */#end
    
    @ApiModelProperty("$column.comment")
    @TableId(value = "$column.obj.name")
    private $!{tool.getClsNameByFullName($column.type)} $!{column.name};
#end
#foreach($column in $tableInfo.otherColumn)
    #if(${column.comment})/**
    * ${column.comment}
    */#end
    
    @ApiModelProperty("$column.comment")
    private $!{tool.getClsNameByFullName($column.type)} $!{column.name};
#end

    @Override
    public String toString(){
        return "$tableInfo.name {" +
        #foreach($column in $tableInfo.fullColumn)
    "$column.name : " + $column.name + ", " +
        #end        
'}';
    }
}

dao

##导入宏定义
$!define

##设置表后缀(宏定义)
#setTableSuffix("Dao")

##保存文件(宏定义)
#save("/dao", "Dao.java")

##包路径(宏定义)
#setPackageSuffix("dao")

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;
import org.apache.ibatis.annotations.Mapper;
##表注释(宏定义)
#tableComment("表数据库访问层")
@Mapper
public interface $!{tableName} extends BaseMapper<$!tableInfo.name> {

}

service

##导入宏定义
$!define

##设置表后缀(宏定义)
#setTableSuffix("Service")

##保存文件(宏定义)
#save("/service", "Service.java")

##包路径(宏定义)
#setPackageSuffix("service")

import com.baomidou.mybatisplus.extension.service.IService;
import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;

##表注释(宏定义)
#tableComment("表服务接口")
public interface $!{tableName} extends IService<$!tableInfo.name> {

}

serviceImpl

##导入宏定义
$!define

##设置表后缀(宏定义)
#setTableSuffix("ServiceImpl")

##保存文件(宏定义)
#save("/service/impl", "ServiceImpl.java")

##包路径(宏定义)
#setPackageSuffix("service.impl")

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import $!{tableInfo.savePackageName}.dao.$!{tableInfo.name}Dao;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.stereotype.Service;

##表注释(宏定义)
#tableComment("表服务实现类")
@Service("$!tool.firstLowerCase($tableInfo.name)Service")
public class $!{tableName} extends ServiceImpl<$!{tableInfo.name}Dao, $!{tableInfo.name}> implements $!{tableInfo.name}Service {

}

controller

##导入宏定义
$!define

##设置表后缀(宏定义)
#setTableSuffix("Controller")

##保存文件(宏定义)
#save("/controller", "Controller.java")

##包路径(宏定义)
#setPackageSuffix("controller")

##定义服务名
#set($serviceName = $!tool.append($!tool.firstLowerCase($!tableInfo.name), "Service"))

##定义实体对象名
#set($entityName = $!tool.firstLowerCase($!tableInfo.name))
#set($PkType = $!{tool.getClsNameByFullName($!tableInfo.pkColumn[0].type)})

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import com.study.first.common.ResultData;

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

##表注释(宏定义)
#tableComment("表控制层")
@RestController
@Api(tags = "$!{tableInfo.comment}($!{tableInfo.name})")
@RequestMapping("$!tool.firstLowerCase($!tableInfo.name)")
public class $!{tableName} {
    /**
     * 服务对象
     */
    @Resource
    private $!{tableInfo.name}Service $!{serviceName};

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param $!entityName 查询实体
     * @return 所有数据
     */
    @GetMapping("/selectAll")
    @ApiOperation(value = "分页查全部")
    public ResultData selectAll(Page<$!tableInfo.name> page, @ApiParam $!tableInfo.name $!entityName) {
		Page<$!tableInfo.name> result = this.$!{serviceName}.page(page, new QueryWrapper<>($!entityName));
        if(result != null){
            return ResultData.success(result);
        }
        return ResultData.error("查询失败");
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/getById/{id}")
    @ApiOperation(value = "根据id查")
    public ResultData selectOne(@PathVariable("id") $!{PkType} id) {
        $tableInfo.name result = $!{tool.firstLowerCase($tableInfo.name)}Service.getById(id);
        if(result != null){
          return ResultData.success(result);
        }
        return ResultData.error("查询失败");
    }

    /**
     * 新增数据
     *
     * @param $!entityName 实体对象
     * @return 新增结果
     */
    @PostMapping("/insert")
    @ApiOperation(value = "添加")
    public ResultData insert(@RequestBody @ApiParam $!tableInfo.name $!entityName) {
		boolean save = this.$!{serviceName}.save($!entityName);
		if (save) {
          return ResultData.success($!tool.firstLowerCase($tableInfo.name));
        }
        return ResultData.error("新增失败");
    }

    /**
     * 修改数据
     *
     * @param $!entityName 实体对象
     * @return 修改结果
     */
    @PutMapping("/update")
    @ApiOperation(value = "更新")
    public ResultData update(@RequestBody @ApiParam $!tableInfo.name $!entityName) {
		boolean update = this.$!{serviceName}.updateById($!entityName);
		if (update) {
          return ResultData.success($!tool.firstLowerCase($tableInfo.name));
        }
        return ResultData.error("更新失败");
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    @ApiOperation(value = "删除")
    public ResultData delete(@RequestParam("idList") @ApiParam List<$!{PkType}> idList) {
		boolean remove = this.$!{serviceName}.removeByIds(idList);
		if (remove) {
          return ResultData.success(remove);
        }
        return ResultData.error("删除失败");
    }
}

在IDEA DataSource上选择需要生成代码的表 右键——>EasyCode——>Generate Code
在这里插入图片描述
pom文件引入maven坐标

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.19</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>
        <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>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-core</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
    </dependencies>

添加application属性文件

server.port=8080

spring.datasource.username=test
spring.datasource.password=test
spring.datasource.url=jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#Spring Boot2.6以上与Swagger2冲突的问题解决
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

mybatis-plus.mapper-locations=classpath:mapper/*.xml
#配置控制台打印完整带参数SQL语句
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

配置swagger

package com.study.first.config;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 1. swagger配置类
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //是否开启 (true 开启  false隐藏。生产环境建议隐藏)
                //.enable(false)
                .select()
                //扫描的路径包,设置basePackage会将包下的所有被@Api标记类的所有方法作为api
                .apis(RequestHandlerSelectors.basePackage("com.study.first.controller"))
                //指定路径处理PathSelectors.any()代表所有的路径
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //设置文档标题(API名称)
                .title("finance web")
                //文档描述
                .description("接口说明")
                //服务条款URL
                .termsOfServiceUrl("http://localhost:8080/")
                //版本号
                .version("1.0.0")
                .build();
    }
}

配置mybaitisPlus分页插件

package com.study.first.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
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;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author yuanzeyu
 * @since 2022/4/7 16:23
 */
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }

}

放上模板中使用的传参类接收类

package com.study.first.common;

import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;

/**
 * 接口请求值统一对象
 *
 * @author yuanzeyu
 * @since 2022/4/7 16:23
 **/
@Data
@NoArgsConstructor
public class RequestData<T> implements Serializable {
	private static final long serialVersionUID = -417976081369662474L;
	private String requestId;
	/**成功时具体返回值,失败时为 null**/
	private T data;
}

package com.study.first.common;

/**
 * 状态码
 *
 * @author yuanzeyu
 * @since 2022/4/7 16:23
 */
public class ResultCode {

    /**
     * 请求成功
     */
    public static Integer SUCCESS=200;
    /**
     * 请求失败
     */
    public static Integer ERROR=201;
    /**
     * 参数错误
     */
    public static Integer PARAM_ERROR=202;
    /**
     * 数据重复
     */
    public static Integer DATE_REPETITION=203;
    /**
     * 服务器错误
     */
    public static Integer SERVER_ERROR=500;
    /**
     * 无数据
     */
    public static Integer NO_DATA=400;

}

package com.study.first.common;

import java.io.Serializable;
import java.util.List;

/**
 * 接口返回值统一对象
 *
 * @author yuanzeyu
 * @since 2022/4/7 16:23
 */
public class ResultData implements Serializable {
    /**
     * true:成功   false:失败
     */
	private boolean status;
    /**
     * 成功时具体返回值,失败时为 null
     */
	private Object data;
    /**
     * 返回具体消息
     */
	private String msg;
    /**
     * 返回具体消息
     */
    private String message;
    /**
     * 返回具体错误码
     */
	private Integer code;
    /**
     * 保留字段
     */
    private String reserved;
    /**
     * 返回具体消息
     */
	private List<String> errorList;

	private String successMsg = "操作成功";
	private String errorMsg = "操作失败";
	private String successMsgEn = "SUCCESS";
	private String errorMsgEn = "FAILED";

	public static ResultData Result(boolean status, String msg, Object data) {
		ResultData result = new ResultData();
		result.setData(data);
		result.setStatus(status);
		result.setMsg(msg);
        result.setMessage(msg);
		return result;
	}

	public static ResultData Result(boolean status, Integer code, String msg, Object data) {
		ResultData result = new ResultData();
		result.setData(data);
		result.setStatus(status);
		result.setCode(code);
		result.setMsg(msg);
        result.setMessage(msg);
		return result;
	}
	
    public static ResultData Result(boolean status, Integer code, String msg, String reserved, Object data) {
        ResultData result = new ResultData();
        result.setData(data);
        result.setStatus(status);
        result.setCode(code);
        result.setMsg(msg);
        result.setMessage(msg);
        result.setReserved(reserved);
        return result;
    }
    
	public static ResultData Result(RuntimeException e) {
		ResultData result = new ResultData();
		result.setStatus(false);
		result.setCode(ResultCode.ERROR);
		result.setMsg(e.getMessage());
        result.setMessage(e.getMessage());
		return result;
	}

	//返回成功
	public static ResultData success() {
		ResultData result = new ResultData();
		result.setStatus(true);
		result.setCode(ResultCode.SUCCESS);
		result.setMsg("操作成功");
        result.setMessage("操作成功");
		return result;
	}

	//返回成功
	public static ResultData success(Object data) {
		ResultData result = new ResultData();
		result.setData(data);
		result.setStatus(true);
		result.setCode(ResultCode.SUCCESS);
		result.setMsg("操作成功");
        result.setMessage("操作成功");
		return result;
	}

	//返回失败
	public static ResultData error() {
		ResultData result = new ResultData();
		result.setStatus(false);
		result.setCode(ResultCode.ERROR);
		result.setMsg("操作失败");
        result.setMessage("操作失败");
        return result;
	}

	public static ResultData error(String msg) {
		ResultData result = new ResultData();
		result.setStatus(false);
		result.setCode(ResultCode.PARAM_ERROR);
		result.setMsg(msg);
        result.setMessage(msg);
        return result;
	}

	public static ResultData error(List<String> errorList) {
		ResultData result = new ResultData();
		result.setStatus(false);
		result.setCode(ResultCode.PARAM_ERROR);
		result.setErrorList(errorList);
		return result;
	}
    
    public String getMessage() {
        return message;
    }
    
    public void setMessage(String message) {
        this.message = message;
    }
    
    public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public List<String> getErrorList() {
		return errorList;
	}

	public void setErrorList(List<String> errorList) {
		this.errorList = errorList;
	}
    
    public String getReserved() {
        return reserved;
    }
    
    public void setReserved(String reserved) {
        this.reserved = reserved;
    }
}

启动项目 运行swagger http://localhost:8080/swagger-ui.html#/
在这里插入图片描述
还可以引用knife4j文档这种 换一种风格的接口文档工具

			<dependency>
                <groupId>com.github.xiaoymin</groupId>
                <artifactId>knife4j-spring-boot-starter</artifactId>
                <!--在引用时请在maven中央仓库搜索2.X最新版本号-->
            </dependency>

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值