MyBatis-Plus代码生成配置

mybatis-plus一键生成配置

pom依赖配置

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.6.RELEASE
    
    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            2.2.0
        
        
        
            mysql
            mysql-connector-java
        
        
        
            junit
            junit
        
        
        
            org.apache.velocity
            velocity-engine-core
            2.0
        
    

配置类配置

GeneratorCode

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 GeneratorCode {
	//主方法中配置
    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        ResourceBundle rb = ResourceBundle.getBundle("mybatis-plus-user");
        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("com.mysql.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);// 表名生成策略
        strategy.setInclude(new String[]{"t_product"}); // 需要生成的表
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(rb.getString("parent"));
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setEntity("domain");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

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

        List focList = new ArrayList();

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

        // 调整 controller 生成目录演示
        focList.add(new FileOutConfig("/template/controller.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirBase2")+ "/com/cdebai/example/web/controller/" + tableInfo.getEntityName() + "Controller.java";
            }
        });

        //query
        focList.add(new FileOutConfig("/template/query.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirBase")+ "/com/cdebai/example/query/" + tableInfo.getEntityName() + "Query.java";
            }
        });

        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml")+ "/com/cdebai/example/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();
    }

}

properties资源文件配置

文件名:mybatis-plus-user

#此处为本项目src所在路径(代码生成器输出路径),注意一定是当前项目所在的目录哟
OutputDir=D:/WorkSpace/example_parent/example_product_parent/example_product_service/src/main/java
#mapper.xml SQL映射文件目录
OutputDirXml=D:/WorkSpace/example_parent/example_product_parent/example_product_service/src/main/resources

OutputDirBase=D:/WorkSpace/example_parent/example_product_parent/example_product_interface/src/main/java
OutputDirBase2=D:/WorkSpace/example_parent/example_product_parent/example_product_service/src/main/java
#设置作者
author=cdebai
#自定义包路径
parent=com.cdebai.example

#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///example
jdbc.user=root
jdbc.pwd=root

template模板文件定义配置
存放于resources/template下

  • query(模板文件名:query.java.vm)
package com.cdebai.example.query;
/**
 *
 * @author ${author}
 * @since ${date}
 */
public class ${table.entityName}Query extends BaseQuery{
}
  • controller(模板文件名:controller.java.vm)
    定义了两个工具类(AjaxResult、PageList)导入会报错,提示没有这两个类,可以自己创建,避免报错。
package ${package.Controller};

import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import com.cdebai.example.query.${entity}Query;
import com.cdebai.example.util.AjaxResult;
import com.cdebai.example.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;

    /**
    * 保存和修改公用的
    * @param ${table.entityPath}  传递的实体
    * @return Ajaxresult转换结果
    */
    @RequestMapping(value="/add",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());
        }
    }

    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
    public AjaxResult delete(@PathVariable("id") Integer 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(@RequestParam(value="id",required=true) Long id)
    {
        return ${table.entityPath}Service.selectById(id);
    }

    /**
    * 查看所有的员工信息
    * @return
    */
    @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());
    }
}

工具类示例:

  • AjaxResult(具体业务根据需要进行变换)
package com.cdebai.example.utils;

public class AjaxResult {

    private Boolean success=true;
    private String message="操作成功";
    private Object object;

    //成功方法
    public static AjaxResult me() {
        return new AjaxResult();
    }

    //get/set
    public Boolean getSuccess() {
        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 getObject() {
        return object;
    }

    public AjaxResult setObject(Object object) {
        this.object = object;
        return this;
    }
}
  • PageList (具体业务根据情况而定)
package com.debai.example.utils;

import com.debai.example.domain.User;
import java.util.List;

public class PageList {
    //总数
    private Long total;
    //数据
    private List records;

    //无参构造
    public PageList() {
    }

    //有参构造
    public PageList(Long total, List records) {
        this.total=total;
        this.records=records;
    }

    //get/set
    public Long getTotal() {
        return total;
    }

    public void setTotal(Long total) {
        this.total = total;
    }

    public List getRecords() {
        return records;
    }

    public void setRecords(List records) {
        this.records = records;
    }
}
  • 配置成功!

你可能感兴趣的:(Java)