mybatis plus 代码生成 自定义目标模板

1 ,启动类

 

package com.zhengqing.blog.util;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.*;

public class GenerateCode {

    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        ResourceBundle rb = ResourceBundle.getBundle("zq_blog"); //TODO 配置文件信息
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(rb.getString("OutputDir"));
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setAuthor(rb.getString("author"));
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert());
        dsc.setDriverName(rb.getString("jdbc.driver"));
        dsc.setUsername(rb.getString("jdbc.user"));
        dsc.setPassword(rb.getString("jdbc.pwd"));
        dsc.setUrl(rb.getString("jdbc.url"));
        mpg.setDataSource(dsc);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(new String[] { "t_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 t_user_xxx UserXxx
        strategy.setInclude(new String[]{"t_user"}); // TODO 需要生成的表
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(rb.getString("parent"));
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setEntity("bean");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
                this.setMap(map);
            }
        };

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

        // 调整 bean 生成目录演示
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirBase")+ "/com/zhengqing/blog/bean/" + tableInfo.getEntityName() + ".java";
            }
        });

        // 调整 query 生成目录演示
        focList.add(new FileOutConfig("/templates/query.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirBase")+ "/com/zhengqing/blog/query/" + tableInfo.getEntityName() + "Query.java";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        //controller配置
        focList.add(new FileOutConfig("/templates/controller.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDir")+ "/com/zhengqing/blog/controller/" + tableInfo.getEntityName() + "Controller.java";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml")+ "/com/zhengqing/blog/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
        TemplateConfig tc = new TemplateConfig();
        tc.setService("/templates/service.java.vm");
        tc.setServiceImpl("/templates/serviceImpl.java.vm");
        tc.setEntity(null);
        tc.setMapper("/templates/mapper.java.vm");
        tc.setController(null);
        tc.setXml(null);
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();
    }

}

 

 

2, 模板:

controller.java.vm

 

package ${package.Controller};

import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import com.zhengqing.blog.query.${entity}Query;
import com.zhengqing.blog.util.AjaxResult;
import com.zhengqing.blog.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/${table.entityPath}")
public class ${entity}Controller {
    @Autowired
    public ${table.serviceName} ${table.entityPath}Service;

    /**
     * 保存、修改 【区分id即可】
     * @param ${table.entityPath}  传递的实体
     * @return Ajaxresult转换结果
     */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public AjaxResult save(@RequestBody ${entity} ${table.entityPath}){
        try {
            if(${table.entityPath}.getId()!=null){
                    ${table.entityPath}Service.updateById(${table.entityPath});
            }else{
                    ${table.entityPath}Service.insert(${table.entityPath});
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存对象失败!"+e.getMessage());
        }
    }

    //删除对象信息
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            ${table.entityPath}Service.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除对象失败!"+e.getMessage());
        }
    }

    //获取用户
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public ${entity} get(@PathVariable("id")Long id)
    {
        return ${table.entityPath}Service.selectById(id);
    }


    //查看所有的员工信息
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public List<${entity}> list(){
        return ${table.entityPath}Service.selectList(null);
    }


    /**
    * 分页查询数据:
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @RequestMapping(value = "/json",method = RequestMethod.POST)
    public PageList<${entity}> json(@RequestBody ${entity}Query query) {
        Page<${entity}> page = new Page<${entity}>(query.getPage(),query.getRows());
        page = ${table.entityPath}Service.selectPage(page);
        return new PageList<${entity}>(page.getTotal(),page.getRecords());
    }
}
 

 

query.java.vm

package com.zhengqing.blog.query;

/**
 * @author ${author}
 * @since ${date}
 */
public class ${table.entityName}Query extends BaseQuery{
}

 

3. model:

package com.zhengqing.blog.util;

//Ajax请求响应对象的类
public class AjaxResult {

    private boolean success = true;
    private String message = "操作成功!";
    private Object resultObj;//返回到前台对象
//    private int code=1;//layui:如果成功则默认返回 1 ,失败则返回自定义的code

    // TODO 现在的方式:
    //AjaxResult.me  -》成功
    //AjaxResult.me().setMessage()  -》成功
    //AjaxResult.me.setSuccess(false).setMessage("失败") -》失败
    public static AjaxResult me(){
        return new AjaxResult();
    }

/*  TODO 以前的方式:
    //成功
    public AjaxResult() { }
    //失败并且有提示
    public AjaxResult(String message) {
        this.success = false;
        this.message = message;
    }
    //成功的封装-------------------------------
    public AjaxResult(String msg){
        this.msg = msg;
    }
    //如果调用这个方法,则创建的是成功时的错误信息
    public AjaxResult(String msg,int code){
        this.success = false;
        this.msg = msg;
        this.code = code;
    }
    */

    public boolean isSuccess() {
        return success;
    }

    public AjaxResult setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public AjaxResult setMessage(String message) {
        this.message = message;
        return this;
    }

    public Object getResultObj(){
        return resultObj;
    }

    public AjaxResult setResultObj(Object resultObj){
        this.resultObj = resultObj;
        return this;
    }

}
 

package com.zhengqing.blog.util;

import java.util.ArrayList;
import java.util.List;

//分页工具:
// 1、easyui只需2个属性,total(总数),datas(分页数据)就能实现分页
// 2、layui 需4个属性,code,msg,count(总数),data(分页数据)实现分页
public class PageList<T> {

    private int code=0;
    private String msg;

    private long count;//总条数
    private List<T> data = new ArrayList<>();//装前台当前页的数据

    //提供有参构造方法,方便测试
    public PageList(long count, List<T> data) {
        this.count = count;
        this.data = data;
    }
    //除了有参构造方法,还需要提供一个无参构造方法
    public PageList() { }

    public int getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

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

    public long getCount() {
        return count;
    }

    public void setCount(long count) {
        this.count = count;
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "PageList{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", count=" + count +
                ", data=" + data +
                '}';
    }
}
 

4. maven 配置

 

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.zhengqing</groupId>
    <artifactId>blog</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>MyBlog</name>
    <description>基于Spring Boot搭建的郑清个人博客</description>

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

    <dependencies>
        <!--springboot-web支持: 1、web mvc; 2、restful; 3、jackjson支持; 4、aop ...-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--springboot测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- springboot热部署所需依赖包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--lombok支持:简化代码-getter/setter、toString等代码-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--mysql数据库支持-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mybatis-plus支持 -》 Mybatis-Plus学习官方文档:https://baomidou.oschina.io/mybatis-plus-doc/#/quick-start-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
        <!--模板引擎-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MyBatis-Plus代码生成器提供了自定义模板的功能,可以根据自己的需求生成对应的代码。下面是自定义模板的处理步骤: 1. 在代码生成器的配置文件中,设置自定义模板的路径。例如: ``` <property name="templatePath" value="/templates/mybatis-plus"/> ``` 2. 在自定义模板路径下创建对应的模板文件。例如,创建一个模板文件 `Entity.java.vm`,用于生成实体类的代码。 3. 在模板文件中使用 Velocity 模板语言,编写生成代码的逻辑。例如: ``` package ${package_name}.${module_name}.entity; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * ${table_comment} * </p> */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("${table_name}") public class ${entity_name} { private static final long serialVersionUID = 1L; #foreach($field in $fields) /** * ${field.comment} */ private ${field.javaType} ${field.name}; #end } ``` 4. 在代码生成器中配置要使用的自定义模板。例如: ``` <property name="templateConfig"> <bean class="com.baomidou.mybatisplus.generator.config.TemplateConfig"> <property name="entity" value="/templates/mybatis-plus/Entity.java.vm"/> <property name="mapper" value="/templates/mybatis-plus/Mapper.java.vm"/> <property name="xml" value="/templates/mybatis-plus/Mapper.xml.vm"/> <property name="service" value="/templates/mybatis-plus/Service.java.vm"/> <property name="serviceImpl" value="/templates/mybatis-plus/ServiceImpl.java.vm"/> <property name="controller" value="/templates/mybatis-plus/Controller.java.vm"/> </bean> </property> ``` 在这个例子中,我们配置了生成实体类、Mapper接口、Mapper XML文件、Service接口、Service实现类和Controller类的模板路径。 5. 运行代码生成器,即可根据自定义模板生成对应的代码。 注意:自定义模板的命名必须与 MyBatis-Plus 内置模板的命名一致,才能正确覆盖内置模板。例如,要自定义生成实体类的模板,必须将模板文件命名为 `Entity.java.vm`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sunday_ding

一分钱也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值