zoukankan      html  css  js  c++  java
  • MyBatis代码生成器MyBatisPlus-generator(自定义模板引擎)

    1.导包

    <!--mybatisplus的包-->
                <dependency>
                    <groupId>com.baomidou</groupId>
                    <artifactId>mybatis-plus-boot-starter</artifactId>
                    <version>2.2.0</version>
                </dependency>
                <!--连接数据库-->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>5.1.6</version>
                </dependency>
    
                <!-- druid连接池的包 -->
                <dependency>
                    <groupId>com.alibaba</groupId>
                    <artifactId>druid</artifactId>
                    <version>1.1.10</version>
                </dependency>
    
    
                <!--模板引擎-->
                <dependency>
                    <groupId>org.apache.velocity</groupId>
                    <artifactId>velocity-engine-core</artifactId>
                    <version>2.0</version>
                </dependency>

    2.写一个properties文件

    创建配置文件 resources/mybatiesplus-config.properties

    #代码生成好之后,输出路径 ,基本输出路径
    OutputDir=F:/IDEAWorkSpace/hrm-parent/hrm-systemmange-parnet/hrm-systemmange-service-2010/src/main/java
    #mapper.xml SQL映射文件目录
    OutputDirXml=F:/IDEAWorkSpace/hrm-parent/hrm-systemmange-parnet/hrm-systemmange-service-2010/src/main/resources
    
    #我们需要的公共包的特殊路径
    OutputDirCommon=F:/IDEAWorkSpace/hrm-parent/hrm-systemmange-parnet/hrm-systemmange-common/src/main/java
    
    #设置作者
    author=jiedada
    
    #自定义包路径
    parent=cn.jiedada.hrm
    
    #数据库连接信息
    
    jdbc.url=jdbc:mysql:///hrm-systemmanage
    jdbc.user=root
    jdbc.pwd=123456
    jdbc.driver=com.mysql.jdbc.Driver

     在resources下面我们还自己创建了一个controller和query

    templates

    controller.java.vm

    package ${package.Controller};
    
    import ${package.Service}.${table.serviceName};
    import ${package.Entity}.${entity};
    import cn.itsource.hrm.query.${entity}Query;
    import cn.itsource.hrm.util.AjaxResult;
    import cn.itsource.hrm.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="/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());
        }
    }

    query.java.vm

    package cn.itsource.hrm.query;
    
    
    /**
     *
     * @author ${author}
     * @since ${date}
     */
    public class ${table.entityName}Query extends BaseQuery{
    }

    3.使用一个主配置类

    通过该类生成我们需要的文件,及文件位置(检查每个配置类,如果有需要这自己写入AjaxRsult,PageList,BaseQuery等分页工具)

    package cn.jiedada;
    
    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.*;
    
    /**
     * Created by CDHong on 2018/4/6.
     * 通过主方法生成我们的mapper,service,controller
     */
    public class GenteratorCode {
    
        public static void main(String[] args) throws InterruptedException {
            //用来获取Mybatis-Plus.properties文件的配置信息
            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(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);// 表名生成策略
    
            strategy.setInclude(new String[]{"t_systemdictionary","t_systemdictionaryitem"}); // 需要生成的表
    
            mpg.setStrategy(strategy);
            // 包配置
            PackageConfig pc = new PackageConfig();
            pc.setParent(rb.getString("parent"));
            pc.setController("web.controller"); //cn.itsource.hrm.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>();
    
            // 调整 controller 生成目录演示
            focList.add(new FileOutConfig("/templates/controller.java.vm") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    //输出的位置
                    return rb.getString("OutputDir")+ "/cn/jiedada/hrm/web/controller/" + tableInfo.getEntityName() + "Controller.java";
                }
            });
    
            // 调整 query 生成目录演示
            focList.add(new FileOutConfig("/templates/query.java.vm") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    //输出的位置
                    return rb.getString("OutputDirCommon")+ "/cn/jiedada/hrm/query/" + tableInfo.getEntityName() + "Query.java";
                }
            });
    
    
            // 调整 domain 生成目录演示
            focList.add(new FileOutConfig("/templates/entity.java.vm") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    //输出的位置
                    return rb.getString("OutputDirCommon")+ "/cn/jiedada/hrm/domain/" + tableInfo.getEntityName() + ".java";
                }
            });
    
            // 调整 xml 生成目录演示
            focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return rb.getString("OutputDirXml")+ "/cn/jiedada/hrm/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); //domain
            tc.setMapper("/templates/mapper.java.vm");
            tc.setController(null);
            tc.setXml(null);
            // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
            mpg.setTemplate(tc);
    
            // 执行生成
            mpg.execute();
        }
    
    }
    View Code

     

  • 相关阅读:
    atitit.解决SyntaxError: missing ] after element list"不个object 挡成个str eval ....
    atitit.软件开发概念过滤和投影 数据操作
    atitit.词法分析的实现token attilax总结
    Atitit.软件gui按钮and面板通讯子系统(区) github 的使用....
    Atitit.解决org.hibernate.DuplicateMappingException: Duplicate class/entity mapping
    atitit.故障排除 当前命令发生了严重错误。应放弃任何可能产生的结果sql server 2008
    Atitit.注解解析(1)词法分析 attilax总结 java .net
    atitit.软件开发GUI 布局管理优缺点总结java swing wpf web html c++ qt php asp.net winform
    atitit.报表最佳实践oae 与报表引擎选型
    Atitit. 解决unterminated string literal 缺失引号
  • 原文地址:https://www.cnblogs.com/xiaoruirui/p/11962452.html
Copyright © 2011-2022 走看看