spring-boot mybatis-plus 集成 + 代码生成器自定义模板
     2019-02-27 14:33:40   深圳市 阅读数 33 点赞 收藏 举报 编辑

注意:

  1. spring boot 和 thymeleaf 结合 controller 返回的控制器路径不能以/ 开头
  2. 否则运行没问题,发布之后就找不到文件



maven依赖

<properties>
    <mybatisplus-spring-boot-starter.version>1.0.4</mybatisplus-spring-boot-starter.version>
    <mybatisplus.version>2.1.0</mybatisplus.version>
</properties>

<!-- mybatis-plus begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>${mybatisplus-spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybatisplus.version}</version>
</dependency>

<!-- 模板引擎 代码生成 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>



生成文件入口类

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.stdd.common.core.ProjectConstant;

public class CodeGenerator_1 {


private static final String JDBC_URL = "jdbc:mysql://39.108.221.220:3306/stdd_db";
private static final String JDBC_USERNAME = "testDB1";
private static final String JDBC_PASSWORD = "fanyuTEST@2018";
private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver";

private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径
private static final String TEMPLATE_FILE_PATH = PROJECT_PATH + "/a-Generator/src/test/resources/generator/template";//模板位置

private static final String JAVA_PATH = "/a-Generator/src/main/java"; //java文件路径
private static final String RESOURCES_PATH = "/a-Generator/src/main/resources";//资源文件路径

private static final String PACKAGE_PATH_SERVICE = packageConvertPath(ProjectConstant.SERVICE_PACKAGE);//生成的Service存放路径
private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(ProjectConstant.SERVICE_IMPL_PACKAGE);//生成的Service实现存放路径
private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(ProjectConstant.CONTROLLER_PACKAGE);//生成的Controller存放路径

/**
* <p>
* MySQL 生成演示
* </p>
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Veloctiy
// mpg.setTemplateEngine(new FreemarkerTemplateEngine());

// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(PROJECT_PATH + JAVA_PATH);
gc.setFileOverride(true);
// 实体类是否需要继承Model<> ,不需要ActiveRecord特性的请改为false
gc.setActiveRecord(false);
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
//gc.setKotlin(true);//是否生成 kotlin 代码
gc.setAuthor("your name");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
// gc.setMapperName("%sDao");
// gc.setXmlName("%sDao");
// gc.setServiceName("MP%sService");
// gc.setServiceImplName("%sServiceDiy");
// gc.setControllerName("%sAction");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert() { // 自定义数据库表字段类型转换【可选】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("转换类型:" + fieldType); // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
return super.processTypeConvert(fieldType);
}
});
dsc.setDriverName(JDBC_DIVER_CLASS_NAME);
dsc.setUsername(JDBC_USERNAME);
dsc.setPassword(JDBC_PASSWORD);
dsc.setUrl(JDBC_URL +"?characterEncoding=utf8");
mpg.setDataSource(dsc); // 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
// 此处可以修改为您的表前缀
//strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });
// 表名生成策略
strategy.setNaming(NamingStrategy.underline_to_camel);
// 需要生成的表
strategy.setInclude(new String[]{"t_im_chat"});
// strategy.setExclude(new String[]{"test"}); // 排除生成的表
// 自定义实体父类
strategy.setSuperEntityClass(null);
// 自定义实体,公共字段
// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
// 自定义 mapper 父类
strategy.setSuperMapperClass("com.stdd.common.tkmapper.MyMapper");
// 自定义 service 父类
// strategy.setSuperServiceClass("com.baomidou.demo.TestService");
// 自定义 service 实现类父类
// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
// 自定义 controller 父类
// strategy.setSuperControllerClass("com.baomidou.demo.TestController");
// 【实体】是否生成字段常量(默认 false)---是否为实体类生成表所有字段的静态常量,
strategy.setEntityColumnConstant(false);
// 【实体】是否为生成的set方法添加返回值,默认false
//strategy.setEntityBuilderModel(false);
//【实体】是否使用lombok框架的@Data注解自动生成get/set方法
strategy.setEntityLombokModel(true);
mpg.setStrategy(strategy); // 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.stdd");
pc.setController("controller");
pc.setEntity("model");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setMapper("dao");
pc.setXml("resources");
mpg.setPackageInfo(pc); // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 ${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() + "-mp");
// this.setMap(map);
// }
// }; // 自定义 xxListIndex.html 生成
// List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// focList.add(new FileOutConfig("/templatesMybatis/list.html.vm") {
// @Override
// public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称
// return "E://test//html//" + tableInfo.getEntityName() + "ListIndex.html";
// }
// });
// cfg.setFileOutConfigList(focList);
// mpg.setCfg(cfg); // 自定义 xxAdd.html 生成
// focList.add(new FileOutConfig("/templatesMybatis/add.html.vm") {
// @Override
// public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称
// return "E://test//html//" + tableInfo.getEntityName() + "Add.html";
// }
// });
// cfg.setFileOutConfigList(focList);
// mpg.setCfg(cfg); // 自定义 xxUpdate.html生成
// focList.add(new FileOutConfig("/templatesMybatis/update.html.vm") {
// @Override
// public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称
// return "E://test//html//" + tableInfo.getEntityName() + "Update.html";
// }
// });
// cfg.setFileOutConfigList(focList);
// mpg.setCfg(cfg); // 关闭默认 xml 生成,调整生成 至 根目录
/*TemplateConfig tc = new TemplateConfig();
tc.setXml(null);
mpg.setTemplate(tc);*/

// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
TemplateConfig tc = new TemplateConfig();
// tc.setController("/templatesMybatis/controller.java.vm");
// tc.setService("/templatesMybatis/service.java.vm");
// tc.setServiceImpl("/templatesMybatis/serviceImpl.java.vm");
tc.setEntity("model.java.vm");
// tc.setMapper("/templatesMybatis/mapper.java.vm");
tc.setXml("mapper.xml.vm"); // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
// 打印注入设置【可无】
System.err.println(mpg.getCfg().getMap().get("abc"));
}

private static String packageConvertPath(String packageName) {
return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName);
}

}


模版文件 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.fields}) #if(${field.name} == ${field.propertyName})${field.name}#else${field.name} #end, #end

</sql> #end
</mapper>


模版文件 model.java.vm

package ${package.Entity}; #if(${activeRecord}) import java.io.Serializable; #end
#foreach($pkg in ${table.importPackages}) import ${pkg}; #end
#if(${entityLombokModel}) import com.baomidou.mybatisplus.annotations.Version; import lombok.Data; import lombok.experimental.Accessors; #end

/**
* <p>
* $!{table.comment}
* </p>
*
* @author ${author}
* @since ${date}
*/
#if(${entityLombokModel}) @Data @Accessors(chain = true) #end
#if(${table.convert}) @TableName("${table.name}") #end
#if(${superEntityClass}) public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end { #elseif(${activeRecord}) public class ${entity} extends Model<${entity}> { #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.AUTO) #elseif(${field.convert}) @TableId("${field.name}") #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}") #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(${activeRecord}) @Override protected Serializable pkVal() { #if(${keyPropertyName}) return this.${keyPropertyName}; #else
return this.id; #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
}


自定义模版文件 controller.java.vm

package $

{package.Controller}; #if(${restControllerStyle})import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; #else
import org.springframework.stereotype.Controller; #end
#if(${superControllerClassPackage})import ${superControllerClassPackage}; #end
import com.alibaba.fastjson.JSON;
import com.dcy.constant.Constant;
import com.dcy.model.BootStrapTable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ${package.Service}.${table.serviceName};import ${package.Entity}.${entity};import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map; /**
* @author ${author}
* @since ${date}
*/
#if(${restControllerStyle})@RestController #else
@Controller #end
@RequestMapping("/a#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end") #if(${superControllerClass})

public class $ {
table.controllerName
} extends ${superControllerClass}{ #else

public class $ {
table.controllerName
} { #end
private final Logger logger=LoggerFactory.getLogger(${table.controllerName}.class);@Autowired public ${table.serviceName}i${entity}Service; /**
* 跳转列表页面
* @param request
* @param model
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = {"/${table.entityPath}Index"}) public String index(HttpServletRequest request,Model model){return"${table.entityPath}ListIndex";} /**
* 分页查询数据
*
* @param bootStrapTable 分页信息
* @param ${table.entityPath} 查询条件
* @return
*/
@ResponseBody @GetMapping("/get${entity}PageList") public Map<String, Object> get${entity}List(BootStrapTable<${entity}>bootStrapTable,${entity}${table.entityPath}){Map<String, Object> result=new HashMap<String, Object>();try{result=bootStrapTable.setRows(i${entity}Service.selectPage(bootStrapTable,${table.entityPath}));}catch(Exception e){logger.error("get${entity}List -=- {}",e.toString());result.put(Constant.BOOTSTAP_TABLE_ROWS,new ArrayList<>());result.put(Constant.BOOTSTRAP_TABLE_TOTAL,0);}return result;} /**
* 跳转添加页面
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/${table.entityPath}Add") public String ${table.entityPath}Add(HttpServletRequest request,HttpServletResponse response,Model model){try{}catch(Exception ex){logger.error("${table.entityPath}Add -=- {}",ex.toString());}return"${table.entityPath}Add";} /**
* 跳转修改页面
* @param request
* @param id 实体ID
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/${table.entityPath}Update") public String ${table.entityPath}Update(HttpServletRequest request,Long id){try{${entity}${table.entityPath}=i${entity}Service.selectById(id);request.setAttribute("${table.entityPath}",${table.entityPath});}catch(Exception ex){logger.error("${table.entityPath}Update -=- {}",ex.toString());}return"${table.entityPath}Upd";} /**
* 保存和修改公用的
* @param ${table.entityPath} 传递的实体
* @return 0 失败 1 成功
*/
@ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/${table.entityPath}Save") public int ${table.entityPath}Save(${entity}${table.entityPath}){int count=0;try{count=i${entity}Service.insertOrUpdate(${table.entityPath})?1:0;}catch(Exception e){logger.error("${table.entityPath}Save -=- {}",e.toString());}return count;} /**
* 根据id删除对象
* @param id 实体ID
* @return 0 失败 1 成功
*/
@ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/${table.entityPath}Delete") public int ${table.entityPath}Delete(Long id){int count=0;try{count=i${entity}Service.deleteById(id)?1:0;}catch(Exception e){logger.error("${table.entityPath}Delete -=- {}",e.toString());}return count;} /**
* 批量删除对象
* @param item 实体集合ID
* @return 0 失败 1 成功
*/
@ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/${table.entityPath}BatchDelete") public int deleteBatchIds(String item){int count=0;try{List<Long> ids=(List<Long>)JSON.parse(item);count=i${entity}Service.deleteBatchIds(ids)?1:0;}catch(Exception e){logger.error("${table.entityPath}BatchDelete -=- {}",e.toString());}return count;}}


自定义模版文件 mapper.java.vm

package ${package.Mapper}; import ${package.Entity}.${entity}; import ${superMapperClassPackage}; 
/**
* <p>
* $!{table.comment} Mapper 接口
* </p>
*
* @author ${author}
* @since ${date}
*/
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}


自定义模版文件 service.java.vm

package ${package.Service};import com.baomidou.mybatisplus.plugins.Page;
import ${package.Entity}.${entity};import ${superServiceClassPackage};import com.dcy.model.BootStrapTable;

import java.util.List;

/**
* <p>
* $!{table.comment} 服务类
* </p>
*
* @author ${author}
* @since ${date}
*/
public interface $ {table.serviceName} extends ${superServiceClass}<${entity}>{
/**
* 分页查询
* @param bootStrapTable
* @param ${table.entityPath}
* @return
*/
Page<${entity}>selectPage(BootStrapTable<${entity}>bootStrapTable,${entity}${table.entityPath});
List<AppCertificate> selectList(${entity}${table.entityPath});

}
发表评论