mybatis-plus代码生成_tenantdatasourceglobalconfiguration-程序员宅基地

技术标签: java  工具类  mybatis  

代码生成器

依赖:

  <!--mybatis-plus包-->
  <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>

   <!--数据库-->
   <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
   </dependency>

   <!--mybatis分页插件Page使用jar开始-->
   <dependency>
       <groupId>org.mybatis.spring.boot</groupId>
       <artifactId>mybatis-spring-boot-starter</artifactId>
       <version>1.3.2</version>
   </dependency>
   <!--<dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis</artifactId>
       <version>3.4.6</version>
   </dependency>-->
   <!--<dependency>
       <groupId>com.github.pagehelper</groupId>
       <artifactId>pagehelper</artifactId>
       <version>4.1.0</version>
   </dependency>-->
   <dependency>
       <groupId>com.baomidou</groupId>
       <artifactId>mybatis-plus-core</artifactId>
       <version>2.2.0</version>
       <scope>compile</scope>
   </dependency>
   <!--mybatis分页插件Page使用jar结束-->

主类GenteratorCode

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 {

    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        //1、这里要改:读取resources中的配置文件名一致=====================
        ResourceBundle rb = ResourceBundle.getBundle("mybatiesplus-config-system"); //不要加后缀
        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);// 表名生成策略
        //2、这里要改:根据数据库中的哪些表生成======================================
        strategy.setInclude(new String[]{
                "t_department",
                "t_employee",
                "t_meal",
                "t_menu",
                "t_permission",
                "t_role",
                "t_tenant",
                "t_tenant_type",

        }); // 需要生成的表
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(rb.getString("parent"));
        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>();

        //controller的输出配置
        focList.add(new FileOutConfig("/templates/controller.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDir") + "/cn/lin/web/controller/" + tableInfo.getEntityName() + "Controller.java";
            }
        });
        //query的输出配置
        focList.add(new FileOutConfig("/templates/query.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirBase") + "/cn/lin/query/" + tableInfo.getEntityName() + "Query.java";
            }
        });

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

        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml") + "/cn/lin/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.setMapper("/templates/mapper.java.vm");
        tc.setEntity(null);
        tc.setController(null);
        tc.setXml(null);
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);

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

}		

配置文件:

mybatiesplus-config-system.properties

#代码输出基本路径
OutputDir=D:/install/java/idea/workspace/hrm/hrmParent/htm-parent/hrm-system-parent/hrm-system-server-1040/src/main/java

#mapper.xml SQL映射文件目录
OutputDirXml=D:/install/java/idea/workspace/hrm/hrmParent/htm-parent/hrm-system-parent/hrm-system-server-1040/src/main/resources

#domain的输出路径
OutputDirBase=D:/install/java/idea/workspace/hrm/hrmParent/htm-parent/hrm-system-parent/hrm-system-common/src/main/java

#设置作者
author=ly

#自定义包路径:基础包的路径
parent=cn.lin.hrm

#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///hrm-system?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
jdbc.user=root
jdbc.pwd=123456

模板文件:

在resources文件夹下新建templates文件夹:放入controller.java.vm与query.java.vm模板

controller.java.vm

package ${package.Controller};

import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import cn.lin.query.${entity}Query;
import cn.lin.util.AjaxResult;
import cn.lin.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().setSuccess(false).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().setSuccess(false).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 ${package.query};

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

所需jar包:

   <!--导入mybatis-plus包-->
   <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>
   </dependency>

   <!--模板引擎-->
   <dependency>
       <groupId>org.apache.velocity</groupId>
       <artifactId>velocity-engine-core</artifactId>
       <version>2.0</version>
   </dependency>	

使用的服务中需要MybatisPlusConfig

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

//Spring boot方式
@Configuration
@MapperScan("cn.lin.ffs.mapper") //mapper接口扫描
@EnableTransactionManagement  //事务管理
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

主类上不需要@MapperScan

在这里插入图片描述

application.yml中加入

在这里插入图片描述

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_49319251/article/details/109701181

智能推荐

看完这篇文章,你如果还不知道怎么设置Oauth2令牌过期时间算我输_oauth2.0如何设置存储token时间-程序员宅基地

文章浏览阅读3.8k次。OAuth2所生成的AccessToken以及RefreshToken都存在过期时间,当在有效期内才可以拿来作为会话身份发起请求,否者认证中心会直接拦截无效请求提示已过期,那么我们怎么修改这个过期时间来满足我们的业务场景呢?目前一线大厂所使用的的AccessToken的有效期一般都是7200秒,也就是2小时,而且有获取的次数限制,所以发起请求的一方必须通过一定的形式保存到本地,以方便下一次发起请..._oauth2.0如何设置存储token时间

ARM-qt 开发,串口配置_开发板串口如何与qt配置-程序员宅基地

文章浏览阅读1.1k次。在使用终端开发使用串口时,配置串口的方式尤为重要1、要使用串口就先打开串口 int OpenUartPort(const char *UartPort) { int fd; fd = open(UartPort,O_RDWR|O_NONBLOCK); if(fd&lt;0) { perror("open serial port"); ..._开发板串口如何与qt配置

Redis dict_java redis dict-程序员宅基地

文章浏览阅读2.1k次。今天看了redis dict部分的源码(dict.h,dict.c),跟大家分享一下。这两个文件包含了redis的hashtable的接口和实现。Redis中hashtable的主要特点是增量rehash,rehash毕竟是一个耗时的操作,redis把它分摊到hashtable的各个小操作中,从而让字典操作性能曲线比较平滑。既然要增量rehash,就要在一个dict中保留两个hasht_java redis dict

【KELM分类】基于鲸鱼算法优化核极限学习机WOA-KELM实现数据分类附matlab代码_woa优化kelm-程序员宅基地

文章浏览阅读36次。在机器学习领域,数据分类一直是一个重要的研究方向。为了有效地处理大量的数据,研究人员提出了各种各样的分类算法。其中,极限学习机(Extreme Learning Machine,ELM)作为一种快速而有效的分类方法,受到了广泛的关注。然而,传统的ELM算法在处理大规模数据时存在一些问题。_woa优化kelm

社交网络分析SNA——Pajek使用教程(网络描述统计+中心性及子群分析)-程序员宅基地

文章浏览阅读2.6w次,点赞77次,收藏264次。本文所有操作均基于Pajek5.11版本实现,也可官网下载最新版本,差别不大→Pajek下载地址目录一、如何画一个现有网络?二、如何交互式构建一个网络?三、Pajek中如何进行自动布局?四、如何对节点形状进行分类?五、抽取子网、移除边六、寻找最短路径七、计算距离八、如何计算三种中心性指标?九、如何计算并抽取一个网络的最高核?写在最后一、如何画一个现有网络?首先,打开Pajek.exe程序运行该软件,基本界面如下图:打开时界面如下:..._pajek

【python】ModuleNotFoundError: No module named ‘skimage.metrics‘_modulenotfounderror: no module named 'skimage.metr-程序员宅基地

文章浏览阅读6.6k次,点赞6次,收藏6次。程序中需导入如下模块:from skimage.metrics import peak_signal_noise_ratio as compare_psnr报错:ModuleNotFoundError: No module named 'skimage.metrics'尝试重新安装skimage:(pytorch) D:\MINE>pip install scikit-imageRequirement already satisfied: scikit-image in d:\myap_modulenotfounderror: no module named 'skimage.metrics

随便推点

vs2017 + QT5.8.0 error C3615_qt+vs2017 qalgorithms-程序员宅基地

文章浏览阅读269次。error C3615: constexpr 函数 "QAlgorithmsPrivate::qt_builtin_ctz" 不会生成常数表达式 (编译源文件 main.cpp)_qt+vs2017 qalgorithms

c语言一维字符数组转字符串,怎么将无符号char数组转为相应字符串-程序员宅基地

文章浏览阅读1k次。如何将无符号char数组转为相应字符串unsignedcharsrc[6]={0x12,0x32,0x56,0x78,0x90,0xab},如何转为:char[12]={"1232567890ab"}?非常感谢!顺便吐槽下,发现C之类转换比java复杂多了。。------解决思路----------------------unsignedcharsrc[6]={0x12,0..._c语言生成unsigned char数组和字符串的字符串

内存溢出记录_内存溢出有什么记录吗-程序员宅基地

文章浏览阅读208次。内存溢出记录OutOfMemoryError内存溢出OutOfMemoryError内存溢出启动参数增加 -XX:+HeapDumpOnOutOfMemoryError (如果是服务器生产环境一般会有运维提供快照给予分析)当发生内存溢出时;找到jdk目录下jvisualvm 打开,将生成的hprof快照导入,查看信息可以看到内存中对象多的情况找到可能发生内存溢出的代码,再具体分析;如果是服务器上的OOM大致思路差不多,定位到占用比较多的对象,然后进行分析。..._内存溢出有什么记录吗

Element+draggable实现拖拽排序_element draggable-程序员宅基地

文章浏览阅读1k次。vue.draggable一款基于vue的拖拽插件更多的vue.draggable知识 vue.draggable中文文档安装方式yarn add vuedraggablenpm i -S vuedraggable<template> <div id="app"> <div>{{drag?'拖拽中':'拖拽停止'}}</div> <draggable v-model="myArray" chosen-class="_element draggable

AD域首次登陆修改密码设置_域控 首次登录必须更改-程序员宅基地

文章浏览阅读4.6k次。设置pwdLastSet属性,为0首次登陆必须修改密码。_域控 首次登录必须更改

mybatis动态SQL注意事项记录_mybatis动态函数注意点-程序员宅基地

文章浏览阅读350次。1. 多参数如果存在多个参数,则必须要@Param来指定参数名称2. 日期比较数据库类型:datetime这里传入的字符串日期endDate 必须为 2018-11-17 00:00:00.000说明:传入的字符串日期的长度必须和数据库的长度保持一致3. insert后返回主键ID说明: 设置useGeneratedKeys为true,返回数据库自动生成的记录主键idxml方式..._mybatis动态函数注意点