详解使用Mybatis-plus + velocity模板生成自定义的代码
pom.xml文件的配置
com.baomidou mybatis-plus-boot-starter 3.3.0 com.baomidou mybatis-plus-generator 3.1.0 org.apache.velocity velocity 1.7
CodeGenerator配置文件
importjava.text.SimpleDateFormat; importjava.util.Date; importjava.util.HashMap; importjava.util.Map; importcom.baomidou.mybatisplus.annotation.DbType; importcom.baomidou.mybatisplus.annotation.IdType; importcom.baomidou.mybatisplus.generator.AutoGenerator; importcom.baomidou.mybatisplus.generator.InjectionConfig; importcom.baomidou.mybatisplus.generator.config.DataSourceConfig; importcom.baomidou.mybatisplus.generator.config.GlobalConfig; importcom.baomidou.mybatisplus.generator.config.PackageConfig; importcom.baomidou.mybatisplus.generator.config.StrategyConfig; importcom.baomidou.mybatisplus.generator.config.TemplateConfig; importcom.baomidou.mybatisplus.generator.config.rules.NamingStrategy; importlombok.extern.java.Log; /** *代码生成器 */ @Log publicclassCodeGenerator{ //项目存储位置 publicstaticStringPROJECT_GENERATE_DISK="E:\\"; //包名 publicstaticStringPARENT_PACKAGE_NAME="com"; //包名 publicstaticStringPACKAGE_NAME="rent.security"; //数据库地址 publicstaticStringDB_URL="jdbc:mysql://localhost:3306/mp?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"; //数据库实例名 publicstaticStringDRIVER_CLASS_NAME="com.mysql.jdbc.Driver"; //数据库用户 publicstaticStringUSER="root"; //数据库密码 publicstaticStringPASSWORD="root"; //数据库schema publicstaticStringSCHEMA="mp"; //要查询的表名 publicstaticStringTABLE_NAMES="sys_role_menu"; //创建人 publicstaticStringAUTHOR="jmm"; //是否强制带上注解 publicstaticbooleanENABLE_TABLE_FIELD_ANNOTATION=false; //生成的注解带上IdType类型 publicstaticIdTypeTABLE_IDTYPE=null; //生成的Service接口类名是否以I开头默认是以I开头user表->IUserService,UserServiceImpl publicstaticbooleanSERVICE_CLASS_NAME_START_WITHI=false; /** *全局配置 */ privatestaticGlobalConfigGlobalGenerate(){ GlobalConfigconfig=newGlobalConfig(); config.setActiveRecord(false)//不需要ActiveRecord特性的请改为false .setIdType(TABLE_IDTYPE) .setEnableCache(false)//XML二级缓存 .setAuthor(AUTHOR) .setBaseResultMap(true)//XMLResultMap .setBaseColumnList(false)//XMLcolumList .setOutputDir(PROJECT_GENERATE_DISK+"\\java") .setFileOverride(true) .setControllerName("%sController");//自定义文件命名,注意%s会自动填充表实体属性! if(!SERVICE_CLASS_NAME_START_WITHI){ config.setServiceName("%sService"); } returnconfig; } /** *数据源配置 */ privatestaticDataSourceConfigDaoSourceGenerate(){ DataSourceConfigdataSourceConfig=newDataSourceConfig(); DbTypetype=DbType.MYSQL; dataSourceConfig.setDbType(type)//数据库类型 .setUrl(DB_URL)//数据库地址 .setUsername(USER)//数据库用户名 .setPassword(PASSWORD)//数据库密码 .setDriverName(DRIVER_CLASS_NAME)//实例名 .setSchemaName(SCHEMA); returndataSourceConfig; } /** *策略配置 */ privatestaticStrategyConfigStrategyGenerate(){ StrategyConfigstrategyConfig=newStrategyConfig(); strategyConfig.setVersionFieldName("version") .setCapitalMode(true)//全局大写命名ORACLE注意 .setEntityLombokModel(false) .setNaming(NamingStrategy.underline_to_camel)//表名生成策略 .entityTableFieldAnnotationEnable(ENABLE_TABLE_FIELD_ANNOTATION) .setInclude(TABLE_NAMES)//修改替换成你需要的表名,多个表名传数组 .setEntityColumnConstant(true)//【实体】是否生成字段常量(默认false)publicstaticfinalStringID="test_id"; .setEntityBuilderModel(true);//【实体】是否为构建者模型(默认false)publicUsersetName(Stringname){this.name=name;returnthis;} returnstrategyConfig; } /** *自定义模板配置 */ privatestaticTemplateConfigTemplateGenerate(){ TemplateConfigtemplateConfig=newTemplateConfig() .setController("templates/java/controller.java") .setService("templates/java/service.java") .setServiceImpl("templates/java/serviceImpl.java") .setMapper("templates/java/mapper.java"); returntemplateConfig; } privatestaticfinalStringMODULE_NAME="sysRoleMenu"; privatestaticfinalStringCLASS_NAME="SysRoleMenu"; privatestaticfinalStringclass_name="sysRoleMenu"; /** *自定义文件及key */ privatestaticInjectionConfigFileGenerate(){ InjectionConfiginjectionConfig=newInjectionConfig(){ @Override publicvoidinitMap(){//自定义参数 Mapmap=newHashMap<>(); //这些自定义的值在vm模板的语法是通过${cfg.xxx}来调用的。 map.put("moduleName",MODULE_NAME); map.put("ClassName",CLASS_NAME); map.put("className",class_name); map.put("packageName",PARENT_PACKAGE_NAME+"."+PACKAGE_NAME); map.put("author",AUTHOR); map.put("datetime",newSimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(newDate())); this.setMap(map); } }; returninjectionConfig; } /** *包配置 */ publicstaticPackageConfigPackageGenerate(){ PackageConfigpc=newPackageConfig().setParent("com") .setModuleName(PACKAGE_NAME) .setController("controller") .setEntity("domain") .setMapper("dao") .setXml("mapper"); returnpc; } publicstaticvoidmain(String[]args){ //全局配置 GlobalConfigconfig=GlobalGenerate(); //配置数据源 DataSourceConfigdataSourceConfig=DaoSourceGenerate(); //配置策略 StrategyConfigstrategyConfig=StrategyGenerate(); //配置模板 TemplateConfigtemplateConfig=TemplateGenerate(); //自定义值 InjectionConfiginjectionConfig=FileGenerate(); //配置包 PackageConfigpackageConfig=PackageGenerate(); //生成代码 newAutoGenerator().setGlobalConfig(config) .setTemplate(templateConfig)//自定义模板路径 .setCfg(injectionConfig) .setDataSource(dataSourceConfig) .setStrategy(strategyConfig) .setPackageInfo(packageConfig) .execute(); } }
一定要注意!!!InjectionConfig方法中自定义的Map返回对象可以返回给模板调用,调用方法是${cfg.xxx}
vm模板代码实例
package${package.Controller};//这样写是依据步骤2的PackageConfig方法配置 importjava.util.List; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.stereotype.Controller; importorg.springframework.web.bind.annotation.GetMapping; importorg.springframework.web.bind.annotation.PathVariable; importorg.springframework.web.bind.annotation.PostMapping; importorg.springframework.web.bind.annotation.RequestMapping; import${package.Entity}.${cfg.ClassName}; import${package.Service}.${cfg.ClassName}Service; importcom.rent.model.AjaxResult; /** *${cfg.moduleName}Controller * *@author${author} *@date${cfg.datetime} */ @Controller @RequestMapping("/${cfg.moduleName}/${cfg.className}") publicclass${cfg.ClassName}ControllerextendsBaseController @Autowired private${cfg.ClassName}Service${cfg.className}Service; /** *查询${cfg.className}列表 */ @GetMapping("/list") publicTableDataInfolist(@RequestParamintpageNumber,@RequestParamintpageSize){ Page<${cfg.ClassName}>page=${cfg.className}Service.select${cfg.ClassName}Page(pageNumber,pageSize); returnpage; } /** *新增保存${cfg.ClassName} */ @PostMapping("/add${cfg.ClassName}") publicAjaxResultaddSave(${cfg.ClassName}${cfg.ClassName}){ booleanret=${cfg.ClassName}Service.save(${cfg.ClassName}); returnnewAjaxResult(ret,ret?"成功":"失败"); } /** *修改保存${cfg.ClassName} */ @PostMapping("/edit") publicAjaxResulteditSave(${cfg.ClassName}${cfg.ClassName}){ booleanret=${cfg.ClassName}Service.updateById(${cfg.ClassName}); returnnewAjaxResult(ret,ret?"成功":"失败"); } @PostMapping("deleteById") @ApiOperation("根据ID删除${cfg.ClassName}") publicAjaxResult<${cfg.ClassName}>deleteById(Longid){ booleanret=${cfg.ClassName}Service.removeById(id); returnnewAjaxResult(true,ret?"成功":"失败"); } @PostMapping("findById") @ApiOperation("根据ID查询${cfg.ClassName}") publicAjaxResult<${cfg.ClassName}>findById(Longid){ ${cfg.ClassName}user=${cfg.ClassName}Service.getById(id); returnnewAjaxResult(true,"成功",user); } }
最后如果需要更详细的vm调用请参阅官方文档:https://baomidou.com/config/generator-config.html#datasource
到此这篇关于详解使用Mybatis-plus+velocity模板生成自定义的代码的文章就介绍到这了,更多相关Mybatis-plusvelocity生成自定义代码内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。