使用mybatisplus生成增删改查模版代码

事例项目地址:gitee

1.pom依赖

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.3.1</version>
        </dependency>

        <dependency>
            <groupId>com.kangyonggan</groupId>
            <artifactId>freemarker</artifactId>
            <version>1.2.0</version>
        </dependency>

2.freemarker模版代码

在mybatis-plus-generator依赖包下的template包下有许多生成模版

使用mybatisplus生成增删改查模版代码_第1张图片

而freemarker所对应的文件为.ftl后缀,将其复制到自己resource下对应的目录

使用mybatisplus生成增删改查模版代码_第2张图片

这里以controller层为例书写模版代码

package ${package.Controller};

import org.springframework.web.bind.annotation.RequestMapping;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
import org.springframework.beans.factory.annotation.Autowired;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${table.entityName};
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplusgen.utils.response.CommonResponse;

/**
 * 

* ${table.comment!} 前端控制器 *

* * @author ${author} * @since ${date} */
<#if restControllerStyle> @RestController <#else> @Controller </#if> @RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle>${controllerMappingHyphen}<#else>${table.entityPath}</#if>") <#if kotlin> class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if> <#else> <#if superControllerClass??> public class ${table.controllerName} extends ${superControllerClass} { <#else> public class ${table.controllerName} { </#if> @Autowired private ${table.serviceName} ${table.entityPath}Service; @PostMapping("/getList") public CommonResponse getList(@RequestBody ${entity} ${table.entityPath}) { return CommonResponse.ok(${table.entityPath}Service.select${entity}List(${table.entityPath})); } @DeleteMapping("/{id}") public CommonResponse deleteByID(Long id) { boolean b = ${table.entityPath}Service.delete${entity}(id); if (!b) { return CommonResponse.fail(); } return CommonResponse.ok("删除成功"); } @PostMapping("/") public CommonResponse insert(@RequestBody ${entity} ${table.entityPath}) { boolean b = ${table.entityPath}Service.insert${entity}(blogTag); if (!b) { return CommonResponse.fail(); } return CommonResponse.ok("插入成功"); } @PutMapping("/") public CommonResponse update(@RequestBody ${entity} ${table.entityPath}) { boolean b = ${table.entityPath}Service.update${entity}(blogTag); if (!b) { return CommonResponse.fail(); } return CommonResponse.ok("更新成功"); } } </#if>
  1. 配置代码生成器
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;


import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Property;
import org.apache.ibatis.annotations.Mapper;


import java.util.Collections;

public class CodeGenerator {
    public static void main(String[] args) {
        //获取当前项目路径
        String property = System.getProperty("user.dir");
        FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/blog?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC", "root", "数据库密码")
                //全局配置
                .globalConfig(builder -> {
                    builder.author("又菜又爱玩") // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .dateType(DateType.ONLY_DATE) //设置事件策略
                            .commentDate("yyyy-MM-dd") // 注释日期
                            .disableOpenDir()     //生成完成后不打开文件夹
                            .outputDir(property + "/src/main/java"); // 指定输出目录

                })
                //包配置
                .packageConfig(builder -> {
                    builder.parent("com.example.mybatisplusgen") // 设置父包名
                            .moduleName("") // 设置父包模块名
                            .entity("pojo")
                            .service("service")
                            .serviceImpl("service.impl")
                            .controller("controller")
                            .mapper("mapper")
                            .xml("xml")
                            .pathInfo(Collections.singletonMap(OutputFile.xml, property + "/src/main/java/com/example/mybatisplusgen/mapper/xml")); // 设置mapperXml生成路径
                })

                .strategyConfig(builder -> {
                    builder.addInclude("blog_tag") // 设置需要生成的表名
                            .addFieldPrefix("")//指定表的哪些字段去掉
                            .serviceBuilder()//开始设置服务层
                            .formatServiceFileName("%sService")//这里整体为 %s(代表表名)+ 后面的Service
                            .formatServiceImplFileName("%sServiceImpl")
                            .entityBuilder()
                            .enableColumnConstant()//生成字段常量
                            .naming(NamingStrategy.underline_to_camel)//生成符合驼峰命名
                            .enableChainModel()//支持链式书写
                            .enableLombok()//支持lombok
                            .addTableFills(new Property("creat_time", FieldFill.INSERT))
                            .addTableFills(new Property("update_time",FieldFill.INSERT_UPDATE))
                            .logicDeletePropertyName("deleted")//指出逻辑删除
                            .enableTableFieldAnnotation()//提供字段注解
                            .controllerBuilder()
                            .formatFileName("%sController")
                            .enableRestStyle()//生成@restcontroller 风格
                            .mapperBuilder()
                            .superClass(BaseMapper.class)//继承
                            .formatMapperFileName("%sDao")
                            .formatXmlFileName("%sMapper")
                            .mapperAnnotation(Mapper.class);
                })
                // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }
}

4.生成结果

@RestController
@RequestMapping("/blogTag")
public class BlogTagController {
        @Autowired
        private BlogTagService blogTagService;

        @PostMapping("/getList")
        public CommonResponse getList(@RequestBody BlogTag blogTag) {
            return CommonResponse.ok(blogTagService.selectBlogTagList(blogTag));
        }

        @DeleteMapping("/{id}")
        public CommonResponse deleteByID(Long id) {
            boolean b = blogTagService.deleteBlogTag(id);
            if (!b) {
            return CommonResponse.fail();
            }
            return CommonResponse.ok("删除成功");
        }

        @PostMapping("/")
        public CommonResponse insert(@RequestBody BlogTag blogTag) {
            boolean b = blogTagService.insertBlogTag(blogTag);
            if (!b) {
            return CommonResponse.fail();
            }
            return CommonResponse.ok("插入成功");
        }

        @PutMapping("/")
        public CommonResponse update(@RequestBody BlogTag blogTag) {
            boolean b = blogTagService.updateBlogTag(blogTag);
            if (!b) {
            return CommonResponse.fail();
            }
            return CommonResponse.ok("更新成功");
        }
}

你可能感兴趣的:(mybatis,java,spring)