mybatisPlus自动代码生成实例(超级简单使用)
每次新项目的开发,都避免不了建很多的dao层、service等等的文件夹,显得很是麻烦,在此推荐一种可快速生成entity、service、mapper、controller文件,以便节省我们的时间,减少加班。。。。。。
1.pom中导入以下三个包
<!-- 模板 velocity --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency>
<!-- java工具类 --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.5.18</version> </dependency>
<!-- mybatis扩展插件包mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.3</version> </dependency>
2.新建一个类AutoFile
package com.example.vueservice.controller; import cn.hutool.core.collection.CollUtil; import com.baomidou.mybatisplus.enums.FieldFill; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableFill; import com.baomidou.mybatisplus.generator.config.rules.DbType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import java.util.List; public class AutoFile { /** * 测试 run 执行 注意:不生成service接口 注意:不生成service接口 注意:不生成service接口 * <p> * 配置方法查看 {@link ConfigGenerator} * </p> */ public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir("C://");//代码生成存放位置 gc.setFileOverride(true); gc.setActiveRecord(false); gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(false);// XML columList gc.setOpen(true); gc.setAuthor("小明");//此处填写代码生成人姓名 // 自定义文件命名,注意 %s 会自动填充表实体属性! // gc.setMapperName("%sDao"); // gc.setXmlName("%sDao"); gc.setServiceImplName("%sService"); // gc.setServiceImplName("%sServiceDiy"); // gc.setControllerName("%sAction"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("xxx");//数据库用户名 dsc.setPassword("xxx");//数据库密码 dsc.setUrl("jdbc:mysql://xxx:xxxx/xxx?characterEncoding=utf8&allowMultiQueries=true");//数据库连接地址 /*dsc.setTypeConvert(new SqlServerTypeConvert(){ // 自定义数据库表字段类型转换【可选】 @Override public DbColumnType processTypeConvert(String fieldType) { if (fieldType.contains("tinyint") ) { return DbColumnType.BLOB; } // 注意!!processTypeConvert 存在默认类型转换, //如果不是你要的效果请自定义返回、非如下直接返回。 return super.processTypeConvert(fieldType); } });*/ mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setTablePrefix("sys_");// 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 /** * 第一步 * 代码生成需要改动这里,将待生成的表名替换到下面 * * 2017.11.2 */ strategy.setInclude(new String[] { "t_user" }); // 需要生成的表 /** * 第二步 * 去掉表名前缀 * * 2017.11.2 */ strategy.setTablePrefix(new String[] { "t_" });// 此处可以修改为您的表前缀 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 // 自定义实体父类 strategy.setSuperEntityClass("com.mayi.test.base.BaseEntity"); // 自定义实体,公共字段 strategy.setSuperEntityColumns( new String[] {}); // 自定义 mapper 父类 strategy.setSuperMapperClass("com.baomidou.mybatisplus.mapper.BaseMapper"); // 自定义 service 父类 strategy.setSuperServiceImplClass("com.mayi.test.base.BaseService"); // 自定义 controller 父类 strategy.setSuperControllerClass("com.mayi.test.base.BaseController"); //逻辑删除属性名称 strategy.setLogicDeleteFieldName("is_deleted"); List<TableFill> tableFillList= CollUtil.newArrayList(); TableFill fill=new TableFill("update_time", FieldFill.INSERT_UPDATE); tableFillList.add(fill); fill=new TableFill("create_time", FieldFill.INSERT); tableFillList.add(fill); strategy.setTableFillList(tableFillList); // 自定义 service 实现类父类 //strategy.setSuperServiceImplClass("org.ibase4j.core.base.BaseService"); // 自定义 controller 父类 //strategy.setSuperControllerClass("org.ibase4j.core.base.AbstractController"); // 【实体】是否生成字段常量(默认 false) // public static final String ID = "test_id"; // strategy.setEntityColumnConstant(true); // 【实体】是否为构建者模型(默认 false) // public User setName(String name) {this.name = name; return this;} // strategy.setEntityBuliderModel(true); mpg.setStrategy(strategy); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.mayi.test");//此处填写包名 /** * 第三步 * 按模块调整代码放置目录 * * 2017.11.2 */ pc.setEntity("sys.entity"); pc.setMapper("sys.dao"); pc.setXml("sys.dao.mappers"); pc.setServiceImpl("sys.service"); pc.setController("sys.web"); mpg.setPackageInfo(pc); // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值 /*InjectionConfig cfg = new InjectionConfig() { public void initMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("providerClass", "ISysProvider"); map.put("providerClassPackage", "org.ibase4j.provider.ISysProvider"); this.setMap(map); } }; mpg.setCfg(cfg);*/ // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/template 下面内容修改, // 放置自己项目的 src/main/resources/template 目录下, 默认名称一下可以不配置,也可以自定义模板名称 TemplateConfig tc = new TemplateConfig(); tc.setEntity("templates/entity.java.vm"); tc.setMapper("templates/mapper.java.vm"); tc.setXml("templates/mapper.xml.vm"); tc.setServiceImpl("templates/service.java.vm"); tc.setController("templates/controller.java.vm"); mpg.setTemplate(tc); // 执行生成 mpg.execute(); System.out.println("代码生成完毕"); } }
3.导入模板,模板可根据自己的需求修改,在此只提供基础
controller.java.vm
package ${package.Controller}; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.glens.eap.platform.entity.RestResultGenerator; import com.glens.eap.platform.beanvalidator.AddGroup; import com.glens.eap.platform.beanvalidator.EditGroup; import com.glens.eap.platform.beanvalidator.PageGroup; import com.glens.spider.base.BaseQuery; import com.glens.eap.platform.util.ValidateUtil; import ${package.Entity}.${entity}; #if(${restControllerStyle}) import org.springframework.web.bind.annotation.RestController; #else import org.springframework.stereotype.Controller; #end #if(${superControllerClassPackage}) import ${superControllerClassPackage}; #end import ${package.ServiceImpl}.${entity}Service; import cn.hutool.core.util.StrUtil; /** * * @ClassName: ${table.controllerName} * @Description: TODO(这里用一句话描述这个类的作用) * @author ${author} * @date ${date} */ #if(${restControllerStyle}) @RestController #else @Controller #end @RequestMapping(value = "#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end") #if(${superControllerClass}) public class ${table.controllerName} extends ${superControllerClass}<${entity}> { #else public class ${table.controllerName} { #end @Autowired private ${entity}Service ${table.entityPath}Service; @RequestMapping(method = RequestMethod.POST, value = "/add") public void add(${entity} ${table.entityPath}, HttpServletRequest request, HttpServletResponse response) { beanValidator(${table.entityPath}, AddGroup.class); ${table.entityPath}Service.insert(${table.entityPath}); renderResult(response); } @RequestMapping(method = RequestMethod.POST, value = "/edit") public void edit(${entity} ${table.entityPath}, HttpServletRequest request, HttpServletResponse response) { beanValidator(${table.entityPath}, EditGroup.class); ${table.entityPath}Service.updateById(${table.entityPath}); renderResult(response); } @RequestMapping(method = RequestMethod.POST, value = "/delete") public void delete(HttpServletRequest request, HttpServletResponse response, String ids) { ValidateUtil.isNotBlank(ids, "主键参数非法,操作失败,请检查"); List<String> idList = StrUtil.split(ids, ','); ${table.entityPath}Service.deleteBatchIds(idList); renderResult(response); } @RequestMapping(method = RequestMethod.GET, value = "/detail") public void detail(HttpServletRequest request, HttpServletResponse response, String id) { ValidateUtil.isNotBlank(id, "主键参数非法,操作失败,请检查"); ${entity} ${table.entityPath} = ${table.entityPath}Service.selectById(id); renderResult(response, RestResultGenerator.success(${table.entityPath})); } @RequestMapping(method = RequestMethod.GET, value = "/queryList") public void queryList(HttpServletRequest request, HttpServletResponse response) { EntityWrapper<${entity}> wrapper = new EntityWrapper<${entity}>(); List<${entity}> list = ${table.entityPath}Service.selectList(wrapper); renderResult(response, RestResultGenerator.success(list)); } @RequestMapping(method = RequestMethod.GET, value = "/queryPageList") public void queryPageList(HttpServletRequest request, HttpServletResponse response, BaseQuery query) { beanValidator(query, PageGroup.class); EntityWrapper<${entity}> wrapper = new EntityWrapper<${entity}>(); Page<${entity}> pg = new Page<${entity}>(query.getPage(), query.getRows()); Page<${entity}> list = ${table.entityPath}Service.selectPage(pg, wrapper); renderResult(response, RestResultGenerator.success(list)); } }
entity.java.vm
package ${package.Entity}; import com.glens.eap.platform.beanvalidator.EditGroup; import java.io.Serializable; import com.baomidou.mybatisplus.annotations.TableId; #foreach($pkg in ${table.importPackages}) import ${pkg}; #end #if(${entityLombokModel}) import com.baomidou.mybatisplus.annotations.Version; import lombok.Data; import lombok.experimental.Accessors; #end import org.hibernate.validator.constraints.NotBlank; /** * * @ClassName: ${entity} * @Description: TODO(这里用一句话描述这个类的作用) * @author ${author} * @date ${date} */ #if(${entityLombokModel}) @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) #end #if(${table.convert}) @TableName("${table.name}") #end #if(${superEntityClass}) public class ${entity} extends ${superEntityClass} implements Serializable { #else public class ${entity} implements Serializable { #end private static final long serialVersionUID = 1L; ## ---------- BEGIN 字段循环遍历 ---------- #foreach($field in ${table.fields}) #if(${field.keyFlag}) #set($keyPropertyName=${field.propertyName}) #end #if("$!field.comment" != "") /** * ${field.comment} */ #end #if(${field.keyFlag}) ## 主键 #if(${field.keyIdentityFlag}) @TableId(value="${field.name}", type= IdType.ID_WORKER) @NotBlank(message = "主键不能为空", groups={EditGroup.class}) #elseif(${field.convert}) @TableId("${field.name}") @NotBlank(message = "主键不能为空", groups={EditGroup.class}) #else @TableId("${field.name}") @NotBlank(message = "主键不能为空", groups={EditGroup.class}) #end ## 普通字段 #elseif(${field.fill}) ## ----- 存在字段填充设置 ----- #if(${field.convert}) @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) #else @TableField(fill = FieldFill.${field.fill}) #end #elseif(${field.convert}) @TableField("${field.name}") #else @TableField("${field.name}") #end ## 乐观锁注解 #if(${versionFieldName}==${field.name}) @Version #end ## 逻辑删除注解 #if(${logicDeleteFieldName}==${field.name}) @TableLogic #end private ${field.propertyType} ${field.propertyName}; #end ## ---------- END 字段循环遍历 ---------- #if(!${entityLombokModel}) #foreach($field in ${table.fields}) #if(${field.propertyType.equals("boolean")}) #set($getprefix="is") #else #set($getprefix="get") #end public ${field.propertyType} ${getprefix}${field.capitalName}() { return ${field.propertyName}; } #if(${entityBuilderModel}) public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) { #else public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) { #end this.${field.propertyName} = ${field.propertyName}; #if(${entityBuilderModel}) return this; #end } #end #end #if(${entityColumnConstant}) #foreach($field in ${table.fields}) public static final String ${field.name.toUpperCase()} = "${field.name}"; #end #end #if(!${entityLombokModel}) @Override public String toString() { return "${entity}{" + #foreach($field in ${table.fields}) #if($!{velocityCount}==1) "${field.propertyName}=" + ${field.propertyName} + #else ", ${field.propertyName}=" + ${field.propertyName} + #end #end "}"; } #end }
mapper.java.vm
package ${package.Mapper}; import ${package.Entity}.${entity}; import ${superMapperClassPackage}; public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { }
mapper.xml.vm
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="${package.Mapper}.${table.mapperName}"> #if(${enableCache}) <!-- 开启二级缓存 --> <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> #end #if(${baseResultMap}) <!-- 通用查询映射结果 --> <resultMap id="BaseResultMap" type="${package.Entity}.${entity}"> #foreach($field in ${table.fields}) #if(${field.keyFlag})##生成主键排在第一位 <id column="${field.name}" property="${field.propertyName}" /> #end #end #foreach($field in ${table.commonFields})##生成公共字段 <result column="${field.name}" property="${field.propertyName}" /> #end #foreach($field in ${table.fields}) #if(!${field.keyFlag})##生成普通字段 <result column="${field.name}" property="${field.propertyName}" /> #end #end </resultMap> #end #if(${baseColumnList}) <!-- 通用查询结果列 --> <sql id="Base_Column_List"> #foreach($field in ${table.commonFields}) #if(${field.name} == ${field.propertyName})${field.name}#else${field.name} AS ${field.propertyName}#end, #end ${table.fieldNames} </sql> #end </mapper>
service.java.vm
package ${package.ServiceImpl}; import ${package.Entity}.${entity}; import ${package.Mapper}.${table.mapperName}; import ${superServiceImplClassPackage}; import org.springframework.stereotype.Service; /** * * @ClassName: ${entity}Service * @Description: TODO(这里用一句话描述这个类的作用) * @author ${author} * @date ${date} */ @Service public class ${entity}Service extends ${superServiceImplClass}<${table.mapperName}, ${entity}> { }
模板存放位置:
4.最后生成文件目录