【企业级SpringBoot单体项目模板 】——Mybatis-plus自动代码生成

这篇具有很好参考价值的文章主要介绍了【企业级SpringBoot单体项目模板 】——Mybatis-plus自动代码生成。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

  • 😜           :是江迪呀
  • ✒️本文关键词SpringBoot项目模版企业级模版
  • ☀️每日   一言我们之所以这样认为,是因为他们这样说。他们之所以那样说,是因为他们想让我们那样认为。所以实践才是检验真理的唯一准则。

上回我们说了一些开发规范,其实现在你就可以开始写代码了。但是呢效率会很慢,实体类、mapperservice等等这些你都要手动创建,这样效率太低了,遇到一个表中有几十个字段的情况,你可以一上午都在写实体类,而且还不能保证准确性,所以我们需要一个工具替我们生成。

一、使用Velocity模版自动生成代码

我们以生成t_user表为例,表结构如下:

【企业级SpringBoot单体项目模板 】——Mybatis-plus自动代码生成,项目搭建,mybatis,spring boot,java

Generator代码:

package com.shijiangdiya.common;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;

import java.util.*;

public class Generator {
    /**
     * 生成的代码的顶层包名
     */
    private static final String SERVICE_NAME = "code";
    /**
     * 最终包路径
     */
    private static final StringBuilder FINAL_PATH = new StringBuilder();

    /**
     * 表名前缀
     */
    private static String tablePrefix = "t_";


    /**
     * <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);
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    /**
     * 代码生成器
     */
    public static void main(String[] args) {
        // 目标数据表名
        String[] tableName = scanner("表名,多个英文逗号分割").split(",");
        generateByTables(tableName);
    }

    private static void generateByTables(String... tableNames) {
        AutoGenerator mpg = new AutoGenerator();
        mpg.setTemplateEngine(new VelocityTemplateEngine());
        // 全局配置
        GlobalConfig gc = globalGenerate();
        // 包配置
        PackageConfig pc = packageGenerate();
        // 数据库配置
        DataSourceConfig dsc = dataSourceGenerate();
        // 自定义模板
        TemplateConfig tc = templateGenerate();
        // 策略配置
        StrategyConfig strategy = strategyGenerate(tableNames);
        mpg.setGlobalConfig(gc);
        mpg.setDataSource(dsc);
        mpg.setPackageInfo(pc);
        mpg.setTemplate(tc);
        mpg.setStrategy(strategy);
        mpg.execute();
    }

    /**
     * 数据库配置
     *
     * @return 数据源
     */
    private static DataSourceConfig dataSourceGenerate() {
        YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
        yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
        //获取yml里的参数
        Properties properties = yamlMapFactoryBean.getObject();
        String url = properties.getProperty("spring.datasource.url");
        String driver = properties.getProperty("spring.datasource.driver-class-name");
        String username = properties.getProperty("spring.datasource.username");
        String password = properties.getProperty("spring.datasource.password");
        // 数据库配置
        DataSourceConfig dsc = new DataSourceConfig();
        //数据类型
        dsc.setDbType(DbType.MYSQL);
        dsc.setUrl(url);
        dsc.setDriverName(driver);
        dsc.setUsername(username);
        dsc.setPassword(password);
        return dsc;
    }

    /**
     * 全局配置
     *
     * @return 全局配置
     */
    private static GlobalConfig globalGenerate() {
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //是否覆盖文件
        gc.setFileOverride(true);
        // 获取顶层目录
        String projectPath = System.getProperty("user.dir");
        // 获取子项目目录
        String path = Generator.class.getClassLoader().getResource("").getPath();
        String levelPath = path.substring(0, path.indexOf("target") - 1);
        if (!projectPath.equals(levelPath)) {
            FINAL_PATH.append(levelPath);
        } else {
            FINAL_PATH.append(projectPath);
        }
        //输出路径
        gc.setOutputDir(FINAL_PATH + "/src/main/java");
        //作者名称
        gc.setAuthor("shijiangdiya");
        //生成后是否自动打开文件
        gc.setOpen(true);
        // XML 二级缓存
        gc.setEnableCache(false);
        //是否使用swagger2
        gc.setSwagger2(true);
        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setControllerName("%sController");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        //mapper.xml中生成基础resultMap
        gc.setBaseResultMap(true);
        //mapper.xml中生成基础columnList
        gc.setBaseColumnList(true);
        // 主键类型
        gc.setIdType(IdType.ID_WORKER);
        return gc;
    }

    /**
     * 策略配置
     * 主要的表字段映射
     *
     * @param tableName 表名
     * @return 策略配置
     */
    private static StrategyConfig strategyGenerate(String[] tableName) {
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        //表名映射到实体策略,带下划线的转成 驼峰
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //列名映射到类型属性策略,带下划线的转成驼峰
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // 表名和字段名是否大小写
        strategy.setCapitalMode(false);
        //实体类使用lombok
        strategy.setEntityLombokModel(true);
        //controller使用rest接口模式
        strategy.setRestControllerStyle(true);
        // 继承顶层controller 这里是
        strategy.setSuperControllerClass("com.shijiangdiya.config.AbstractController");
        //设置表名
        strategy.setInclude(tableName);
        //去掉前缀
        strategy.setTablePrefix(tablePrefix);
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);
        // 驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setEntityBuilderModel(true);
        return strategy;
    }

    /**
     * 自定义模板
     *
     * @return 模板
     */
    private static TemplateConfig templateGenerate() {
        // 设置自定义的模板
        TemplateConfig tc = new TemplateConfig();
        tc.setController("templates/MyController.java.vm")
                .setEntity("templates/MyEntity.java.vm")
                .setService("templates/MyService.java.vm")
                .setServiceImpl("templates/MyServiceImpl.java.vm")
                .setMapper("templates/MyMapper.java.vm")
                .setXml("/templates/MyMapper.xml.vm");
                // 不要源码包内的mapper
        return tc;
    }

    /**
     * 包配置
     *
     * @return 包配置
     */
    private static PackageConfig packageGenerate() {
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(SERVICE_NAME);
        pc.setParent("com.shijiangdiya");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        pc.setXml("mapper.xml");
        return pc;
    }
}

二、自定义vm模版

使用自定义模板你可以生成更加符合你业务场景的代码。

2.1 MyController.java.vm

在控制层中,提供了CRUD的方法,你可以自定义一些通用的东西,比如传入查询的QO、返回的DTO等。

package ${package.Controller};

import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import com.shijiangdiya.config.Response;


#if(${superControllerClassPackage})
import $!{superControllerClassPackage};
#end


/**
 * <p>
 * $!{table.comment} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
@RestController
@RequestMapping(value = {"#if(${controllerMappingHyphenStyle})/api/${controllerMappingHyphen}#else /api/${table.entityPath}#end"},
		produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "${table.controllerName}", description = "$!{table.comment}", produces = MediaType.APPLICATION_JSON_VALUE)
public class ${table.controllerName} extends ${superControllerClass} {
    @Autowired
    private ${table.serviceName} ${entityName}Service;

    @ResponseBody
    @ApiOperation(value = "", notes = "")
    @GetMapping(value = "/")
    public Response select(){
        ${entityName}Service.select();
        return returnSuccess();
    }

    @ResponseBody
    @ApiOperation(value = "", notes = "")
    @PostMapping(value = "")
    public Response add(){
        ${entityName}Service.add();
        return returnSuccess();
    }

    @ResponseBody
    @ApiOperation(value = "", notes = "")
    @PutMapping(value = "/{id}")
    public Response update(@PathVariable Long id){
        ${entityName}Service.modifyById();
        return returnSuccess();
    }

    @ApiOperation(value = "$!{table.comment}-删除", notes = "$!{table.comment}-删除")
    @DeleteMapping(value = "/{id}")
    public Response delete(@PathVariable Long id){
        ${entityName}Service.deleteById(id);
        return returnSuccess();
    }

}

2.2 MyEntity.java.vm 实体类

package ${package.Controller};

import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import com.shijiangdiya.config.Response;


#if(${superControllerClassPackage})
import $!{superControllerClassPackage};
#end


/**
 * <p>
 * $!{table.comment} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
@RestController
@RequestMapping(value = {"#if(${controllerMappingHyphenStyle})/api/${controllerMappingHyphen}#else /api/${table.entityPath}#end"},
		produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "${table.controllerName}", description = "$!{table.comment}", produces = MediaType.APPLICATION_JSON_VALUE)
public class ${table.controllerName} extends ${superControllerClass} {
    @Autowired
    private ${table.serviceName} ${entityName}Service;

    @ResponseBody
    @ApiOperation(value = "", notes = "")
    @GetMapping(value = "/")
    public Response select(){
        ${entityName}Service.select();
        return returnSuccess();
    }

    @ResponseBody
    @ApiOperation(value = "", notes = "")
    @PostMapping(value = "")
    public Response add(){
        ${entityName}Service.add();
        return returnSuccess();
    }

    @ResponseBody
    @ApiOperation(value = "", notes = "")
    @PutMapping(value = "/{id}")
    public Response update(@PathVariable Long id){
        ${entityName}Service.modifyById();
        return returnSuccess();
    }

    @ApiOperation(value = "$!{table.comment}-删除", notes = "$!{table.comment}-删除")
    @DeleteMapping(value = "/{id}")
    public Response delete(@PathVariable Long id){
        ${entityName}Service.deleteById(id);
        return returnSuccess();
    }

}

2.3 MyMapper.java.vm mapper接口

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.apache.ibatis.annotations.Mapper;

/**
 * <p>
 * $!{table.comment} Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Mapper
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}

2.4 MyMapper.xml.vm mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}">
</mapper>

2.5 MyService.java.vm 服务层

package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import java.util.List;
/**
 * <p>
 * $!{table.comment} 服务类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

    /**
        * 查询
        */
       List select();

       /**
        * 修改
        */
       void add();

       /**
        * 删除
        * @param id
        */
       void deleteById(Long id);

       /**
        * 修改
        */
       void modifyById();
}

2.6 MyServiceImpl.java.vm 服务实现类

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * <p>
 * $!{table.comment} 服务实现类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 * @version ${cfg.version}
 */
#set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
@Service
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

     @Override
       public List select() {
           return null;
       }

       @Override
       public void add() {

       }

       @Override
       public void deleteById(Long id) {

       }

       @Override
       public void modifyById() {

       }
}

三、测试

【企业级SpringBoot单体项目模板 】——Mybatis-plus自动代码生成,项目搭建,mybatis,spring boot,java
【企业级SpringBoot单体项目模板 】——Mybatis-plus自动代码生成,项目搭建,mybatis,spring boot,java文章来源地址https://www.toymoban.com/news/detail-731792.html

到了这里,关于【企业级SpringBoot单体项目模板 】——Mybatis-plus自动代码生成的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • vue2企业级项目(三)

    引入mockjs,i18n 项目下载依赖 根目录创建 mock 文件夹,并创建 mock/index.js 创建 mock/mockPort.js 创建 mock/modules/test.js 示例 src 目录下创建 api/mock.js 示例 main.js 添加一下内容 根目录创建 vue.config.js 项目下载依赖 src 目录下创建 i18n/index.js 文件 main.js 引入使用 i18n ,和 vuex 生成的 s

    2024年02月14日
    浏览(30)
  • vue2企业级项目(四)

    路由设计,过场动画设计 项目下载依赖 src 目录下创建 router/index.js 创建 router/modules 文件,并使用 require.context 技术进行动态引入。 创建 router/hook.js 文件,编写路由拦截等操作 使用 router.addRoutes 方法,动态设置后端传入的路由。(不建议) 前端开发需要路由来找具体的页面

    2024年02月15日
    浏览(41)
  • vue2企业级项目(八)

    4、 searchForm 创建 components/searchForm/index.js 使用案例 5、 searchTable 创建 components/searchTable/index.js 创建 components/searchTable/index.vue 使用案例 6、 dialogForm 创建 components/dialogForm/index.js 创建 components/dialogForm/index.vue 使用案例

    2024年02月14日
    浏览(37)
  • 低代码企业级PMO项目管理系统,360度全景透视企业管理视角

    在一个崇高的目标支持下,不停地工作,即使慢,也一定会获得成功。   爱因斯坦 企业级PMO项目管理业务是行业里相对成熟和规范的业务,拥有众多商业套件和标准产品。 然而随着企业数字化建设进入深水区,站在甲方角度进行项目管理的业务视角、精细化管控、标准化管

    2024年02月03日
    浏览(47)
  • 企业级微服务架构实战项目--xx优选-用户登录

    1.登录常量  2.登录地址  3.配置域名 4.启动程序     触发连接小程序后端的登录接口    小程序controller的登录方法  

    2024年02月11日
    浏览(49)
  • Vue3.0 项目启动(打造企业级音乐App)

    内容 参考链接 Vue3.0 项目启动 Vue3.0 项目启动(打造企业级音乐App) Vue3.0项目——打造企业级音乐App(一) Tab栏、轮播图、歌单列表、滚动组件 Vue3.0项目——打造企业级音乐App(二) 图片懒加载、v-loading指令的开发和优化 2020年09月18日,vue3.0 版本正式发布。这意味着在未来

    2023年04月08日
    浏览(33)
  • 企业级高负载web服务器-Tomcat小项目

    静态页面: 在网站设计中,纯粹HTML格式的网页(可以包含图片、视频JS (前端功能实现)、CSS (样式)等)通常 被称为\\\"静态网页\\\" 特点: 处理文件类型:如.html、jpg、.gif、.mp4、.swf、.avi、.wmv、.flv等2. 地址中不含有问号\\\"?\\\"或等特殊符号。 保存在网站服务器文件系统上的,是

    2024年02月14日
    浏览(35)
  • Redis:原理速成+项目实战——Redis企业级项目实战终结篇(HyperLogLog实现UV统计)

    👨‍🎓作者简介:一位大四、研0学生,正在努力准备大四暑假的实习 🌌上期文章:Redis:原理速成+项目实战——Redis实战14(BitMap实现用户签到功能) 📚订阅专栏:Redis:原理速成+项目实战 希望文章对你们有所帮助 这篇是实战部分的终结篇,其实Redis的核心操作,主要是

    2024年01月17日
    浏览(34)
  • Vue3 + Vite2 + TypeScript4搭建企业级项目框架

    1. 创建项目 使用命令行工具进入到你想要创建项目的目录,然后执行以下命令: 这将会创建一个新的项目文件夹和一个 package.json 文件。 2. 安装依赖 接下来你需要在项目中安装 Vue、Vite、TypeScript 和其他需要的依赖。执行以下命令: 以上命令会安装最新的 Vue、Vite 和 TypeSc

    2024年02月08日
    浏览(43)
  • 企业级开发项目实战——基于RabbitMQ实现数据库、elasticsearch的数据同步

    1、商品上架时:search-service新增商品到elasticsearch 2、商品下架时:search-service删除elasticsearch中的商品 数据同步是希望,当我们商品修改了数据库中的商品信息,索引库中的信息也会跟着改。在微服务中数据库和索引库是在两个不同的服务中。如果,商品的服务,向es的服务中

    2024年02月12日
    浏览(45)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包