springboot集成mybatis-plus自动生成代码

springboot集成mybatis-plus自动生成代码

1.导包


<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-boot-starterartifactId>
    <version>2.2.0version>
dependency>

<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
dependency>

<dependency>
    <groupId>org.apache.velocitygroupId>
    <artifactId>velocity-engine-coreartifactId>
    <version>2.0version>
dependency>

2.resource目录下创建配置文件mybatiesplus-config.properties

#mapper接口,servier,controller输出目录
OutputDir=E:/javaProject/aopdemo/src/main/java
#mapper.xml SQL映射文件目录  这里直接到resources根就可以了  会自动拼接下面的parent在后面
OutputDirXml=E:/javaProject/aopdemo/src/main/resources
#domain,query输出的目录
OutputDirBase=E:/javaProject/aopdemo/src/main/java
#设置作者
author=quyi
#自定义包路径
parent=com.quyi
#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///cms?serverTimezone=GMT%2B8
jdbc.user=root
jdbc.pwd=0

3.拷贝模版文件

在resource文件夹下创建templates文件夹,拷贝controller.java.vm、query.java.vm

3.1:controller.java.vm

package ${package.Controller};

import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
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="/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());
        }
    }

    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @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);
    }


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

        return ${table.entityPath}Service.selectList(null);
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @RequestMapping(value = "/pagelist",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());
    }
}

3.2:query.java.vm

package edu.lzy.query;


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

4.代码生成类

package com.quyi.utils;

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 GenteratorCode {
    //运行main方法就可以生成代码了
    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        //不要加后缀
        final ResourceBundle rb = ResourceBundle.getBundle("mybatiesplus-config");
        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[]{
                "department",
                "address",
        }); // 需要生成的表
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(rb.getString("parent")); //基本包 edu.lzy
        pc.setController("web.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<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
                this.setMap(map);
            }
        };
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        //拼接基本路径
        String parentDir = strRep(rb.getString("OutputDir") + "/" + pc.getParent());
        // 调整 controller 生成目录演示
        focList.add(new FileOutConfig("/templates/controller.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //controller输出完整路径
                return parentDir + "/web/controller/" + tableInfo.getEntityName() + "Controller.java";
            }
        });
        // 调整 query 生成目录演示
        focList.add(new FileOutConfig("/templates/query.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //query输出完整路径
                return parentDir + "/query/" + tableInfo.getEntityName() + "Query.java";
            }
        });
        // 调整 domain 生成目录演示 , 你的domain到底要输出到哪儿????,你的domain怎么输出
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //domain输出完整路径
                return parentDir + "/domain/" + tableInfo.getEntityName() + ".java";
            }
        });
        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml") + "/" + strRep(pc.getParent()) + "/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();
    }
    /*将包名转换为文件夹格式*/
    public static String strRep(String s){
        return s.replace(".","/");
    }
}

5.拷贝需要的工具类和base类

拷贝 PageList、AjaxResult、BaseQuery ,代码放在最后面。

6.需要修改的地方

6.1:mybatiesplus-config.properties;

6.2:修改需要自动生成的表对应的代码;

7.开始生成代码,配置mapper扫描

运行GenteratorCode代码生成类中的主方法,然后修改报错的地方即可。

7.1 配置Mapper接口 扫描

在springboot启动类上打上@MapperScan注解,如:

@MapperScan("Mapper接口包限定名")

7.1 配置Mapper.xml映射 扫描

在springboot配置文件application.yml中加上如下:

# 配置xml映射文件位置
mybatis-plus:
  mapper-locations: classpath:com/quyi/mapper/*Mapper.xml

注意:如果编译之后 mapper接口 和 mapper.xml 映射文件在同一个包下 且 同名,spring扫描Mapper.class的同时会自动扫描同名的Mapper.xml并装配到Mapper.class,那么可以不配置映射扫描,当前代码生成器默认参数生成的可以不加。

8.其他文件

//PageList
package com.quyi.utils;

import java.util.ArrayList;
import java.util.List;
//分页对象:easyui只需两个属性,total(总数),datas(分页数据)就能实现分页
public class PageList<T> {
    private long total;
    private List<T> rows = new ArrayList<>();

    public long getTotal() {
        return total;
    }

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

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }

    @Override
    public String toString() {
        return "PageList{" +
                "total=" + total +
                ", rows=" + rows +
                '}';
    }

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

//AjaxResult
package com.quyi.utils;

//Ajax请求响应对象的类
public class AjaxResult {
    private boolean success = true;
    private String message = "操作成功!";
    //返回到前台对象
    private Object resultObj;



    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;
    }

    /*创建一个对象返回*/
    public static AjaxResult me(){
        return new AjaxResult();
    }


}
//BaseQuery 
package com.quyi.query;


/**
 * 基础查询对象
 */
public class BaseQuery {
    //关键字
    private String keyword;
    //有公共属性-分页
    private Integer page = 1; //当前页
    private Integer rows = 10; //每页显示多少条

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }
}

你可能感兴趣的:(其他)