1.MybatisPlus的功能在Mybatis的基础上只做增强 不做改变
2.逆向工程Generator功能 在原来基础上增加了Controller、Service 层代码
3.支持模板引擎自定义文件的生成配置
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.1.9</version>
</dependency>
package com.example.demo.utils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
*
* @author caocc
*
*/
public class MabatisPlusGenerator {
// 生成文件所在项目路径
private static String baseProjectPath = "E:\\my\\workspace\\demo";
// 静态文件所在项目路径
private static String viewProjectPath = "\\src\\main\\resources\\templates\\view\\";
// 基本包名
private static String basePackage = "com.example.demo";
// 作者
private static String authorName = "only3c";
// 要生成的表名
private static String[] tables = { "city" };
// table前缀
private static String prefix = "";
// 生成自定义文件(html文件)开关
private static Boolean htmlPage = false;
private static File file = new File(basePackage);
private static String path = file.getAbsolutePath();
// 数据库配置四要素
private static String driverName = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true";
private static String username = "root";
private static String password = "password";
private static TableInfo tableInfo = null;
public static void main(String[] args) {
doMpGen();
}
public static void doMpGen() {
System.out.println(path);
//生成静态文件夹 否则静态文件不能生成到指定文件夹
if (htmlPage) {
for (String table : tables) {
File fff = new File(baseProjectPath + viewProjectPath + table.replaceAll("_", ""));
if (!fff.exists()) {
fff.mkdirs();
}
}
}
// 自定义需要填充的字段
List<TableFill> tableFillList = new ArrayList<>();
tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE));
// 1 代码生成器 整合配置
AutoGenerator gen = new AutoGenerator();
/**
* 2 数据库配置
*/
gen.setDataSource(new DataSourceConfig().setDbType(DbType.MYSQL).setDriverName(driverName).setUrl(url)
.setUsername(username).setPassword(password).setTypeConvert(new MySqlTypeConvert() {
// 自定义数据库表字段类型转换【可选】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("转换类型:" + fieldType);
// if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
// return DbColumnType.BOOLEAN;
// }
return super.processTypeConvert(fieldType);
}
}));
/**
* 3 全局配置
*/
gen.setGlobalConfig(new GlobalConfig().setOutputDir(baseProjectPath + "/src/main/java")// 输出目录
.setFileOverride(true)// 是否覆盖文件
.setActiveRecord(true)// 开启 activeRecord 模式
.setEnableCache(false)// XML 二级缓存
.setBaseResultMap(true)// XML ResultMap
.setBaseColumnList(true)// XML columList
.setOpen(false)// 生成后打开文件夹
.setAuthor(authorName)
// 自定义文件命名,注意 %s 会自动填充表实体属性!
.setMapperName("%sMapper").setXmlName("%sMapper").setServiceName("%sService")
.setServiceImplName("%sServiceImpl").setControllerName("%sController"));
/**
* 4 策略配置
*/
gen.setStrategy(new StrategyConfig()
// .setCapitalMode(true)// 全局大写命名
// .setDbColumnUnderline(true)//全局下划线命名
.setTablePrefix(new String[] { prefix })// 此处可以修改为您的表前缀
.setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
.setInclude(tables) // 需要生成的表
.setRestControllerStyle(false)
// .setExclude(new String[]{"gente2"}) // 排除生成的表
// 自定义实体父类
// .setSuperEntityClass("com.baomidou.demo.TestEntity")
// 自定义实体,公共字段
// .setSuperEntityColumns(new String[]{"test_id"})
// .setTableFillList(tableFillList)
// 自定义 mapper 父类 默认BaseMapper
// .setSuperMapperClass("com.baomidou.mybatisplus.mapper.BaseMapper")
// 自定义 service 父类 默认IService
// .setSuperServiceClass("com.baomidou.demo.TestService")
// 自定义 service 实现类父类 默认ServiceImpl
// .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl")
// 自定义 controller 父类
// .setSuperControllerClass("com.caocc.portal.controller.BaseController")
// 【实体】是否生成字段常量(默认 false)
// public static final String ID = "test_id";
// .setEntityColumnConstant(true)
// 【实体】是否为构建者模型(默认 false)
// public User setName(String name) {this.name = name; return this;}
// .setEntityBuilderModel(true)
// 【实体】是否为lombok模型(默认 false)document
// .setEntityLombokModel(true)
// Boolean类型字段是否移除is前缀处理
// .setEntityBooleanColumnRemoveIsPrefix(true)
// .setRestControllerStyle(true)
// .setControllerMappingHyphenStyle(true)
);
/**
* 5 包名策略配置
*/
gen.setPackageInfo(new PackageConfig()
// .setModuleName("User")//模块名称,单独生成模块时使用!!!!!!!!!!!
.setParent(basePackage)// 自定义包路径
.setController("controller")// 这里是控制器包名,默认 web
.setEntity("model")
.setMapper("mapper")
.setService("service")
.setServiceImpl("service.impl")
// .setXml("mapping")
);
/**
* 6 注入自定义配置
*/
// 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
InjectionConfig abc = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
// 自定义文件输出位置(非必须)
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
//自定义MapperXml位置
focList.add(new FileOutConfig("/templates/tv/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return baseProjectPath + "/src/main/resources/mappers/" + tableInfo.getEntityName() + "Mapper.xml";
}
});
if (htmlPage) {
// abc.setFileOutConfigList(fileOutList);
// gen.setCfg(abc);
// 自定义 xxListIndex.html 生成
focList.add(new FileOutConfig("/templates/tv/list.html.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return baseProjectPath + viewProjectPath + tableInfo.getEntityName().toLowerCase() + "/"
+ tableInfo.getEntityName() + "ListIndex.html";
}
});
// abc.setFileOutConfigList(focList);
// gen.setCfg(abc);
// 自定义 xxAdd.html 生成
focList.add(new FileOutConfig("/templates/tv/add.html.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return baseProjectPath + viewProjectPath + tableInfo.getEntityName().toLowerCase() + "/"
+ tableInfo.getEntityName() + "Add.html";
}
});
// abc.setFileOutConfigList(focList);
// gen.setCfg(abc);
// 自定义 xxUpdate.html生成
focList.add(new FileOutConfig("/templates/tv/update.html.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return baseProjectPath + viewProjectPath + tableInfo.getEntityName().toLowerCase() + "/"
+ tableInfo.getEntityName() + "Update.html";
}
});
}
abc.setFileOutConfigList(focList);
gen.setCfg(abc);
// 指定模板引擎 默认是VelocityTemplateEngine ,需要引入相关引擎依赖
// gen.setTemplateEngine(new FreemarkerTemplateEngine());
/**
* 7 模板配置
*/
gen.setTemplate(
new TemplateConfig()
// 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
// 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置:
.setController("/templates/tv/controller.java.vm")
// 关闭默认 xml 生成,调整生成 至 根目录
.setXml(null)
// .setEntity("...")
// .setMapper("...")
// .setService("...")
// .setServiceImpl("...")
);
/**
* 8 执行生成
*/
gen.execute();
List<TableInfo> listti = gen.getConfig().getTableInfoList();
if (listti != null && listti.size() > 0) {
tableInfo = listti.get(0);
System.out.println(tableInfo.getEntityName());
}
System.err.println(gen.getCfg().getMap().get("abc"));
}
}
<?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})
${field.name},
#end
${table.fieldNames}
</sql>
#end
</mapper>
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 org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestParam;
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.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
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;
/**
*
* @author ${author}
* @since ${date}
*/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#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 static final String PATH="${entity}/";
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 PATH+"${table.entityPath}ListIndex";
}
/**
* 分页查询数据
*
* @param bootStrapTable 分页信息
* @param ${table.entityPath} 查询条件
* @return
*/
@ResponseBody
@PostMapping("/get${entity}PageList")
public Page<${entity}> get${entity}List(Page<${entity}> page) {
Page<${entity}> result = new Page<${entity}>();
try {
result = i${entity}Service.selectPage(page, new EntityWrapper<${entity}>());
} catch (Exception e) {
logger.error("get${entity}List -=- {}",e.toString());
}
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 PATH+"${table.entityPath}Add";
}
/**
* 跳转修改页面
* @param request
* @param id 实体ID
* @return
*/
@RequestMapping(method=RequestMethod.GET,value="/${table.entityPath}Update")
public String ${table.entityPath}Update(HttpServletRequest request,@RequestParam(required = true)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 PATH+"${table.entityPath}Upd";
}
/**
* 保存和修改公用的
* @param ${table.entityPath} 传递的实体
* @return 0 失败 1 成功
*/
@ResponseBody
@RequestMapping(method=RequestMethod.POST,value="/${table.entityPath}Save")
public int ${table.entityPath}Save(@RequestBody ${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(@RequestParam(required = true) 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(@RequestParam(required = true) List<Long> ids){
int count = 0;
try {
count = i${entity}Service.deleteBatchIds(ids) ? 1 : 0;
}catch (Exception e){
logger.error("${table.entityPath}BatchDelete -=- {}",e.toString());
}
return count;
}
}
1.使用MabatisPlusGenerator前结构图
2.使用MabatisPlusGenerator后结构图
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestParam;
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.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.example.demo.service.CityService;
import com.example.demo.model.City;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* 自定义后生成Controller展示↓
* @author only3c
* @since 2019-02-28
*/
@Controller
@RequestMapping("/city")
public class CityController {
private static final String PATH="City/";
private final Logger logger = LoggerFactory.getLogger(CityController.class);
@Autowired
public CityService iCityService;
/**
* 跳转列表页面
* @param request
* @param model
* @return
*/
@RequestMapping(method= RequestMethod.GET,value = {"/cityIndex"})
public String index(HttpServletRequest request, Model model) {
return PATH+"cityListIndex";
}
/**
* 分页查询数据
*
* @param bootStrapTable 分页信息
* @param city 查询条件
* @return
*/
@ResponseBody
@PostMapping("/getCityPageList")
public Page<City> getCityList(Page<City> page) {
Page<City> result = new Page<City>();
try {
result = iCityService.selectPage(page, new EntityWrapper<City>());
} catch (Exception e) {
logger.error("getCityList -=- {}",e.toString());
}
return result;
}
/**
* 跳转添加页面
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(method=RequestMethod.GET,value="/cityAdd")
public String cityAdd(HttpServletRequest request,HttpServletResponse response,Model model) {
try {
}catch (Exception ex){
logger.error("cityAdd -=- {}",ex.toString());
}
return PATH+"cityAdd";
}
/**
* 跳转修改页面
* @param request
* @param id 实体ID
* @return
*/
@RequestMapping(method=RequestMethod.GET,value="/cityUpdate")
public String cityUpdate(HttpServletRequest request,@RequestParam(required = true)Long id) {
try {
City city = iCityService.selectById(id);
request.setAttribute("city",city);
}catch (Exception ex){
logger.error("cityUpdate -=- {}",ex.toString());
}
return PATH+"cityUpd";
}
/**
* 保存和修改公用的
* @param city 传递的实体
* @return 0 失败 1 成功
*/
@ResponseBody
@RequestMapping(method=RequestMethod.POST,value="/citySave")
public int citySave(@RequestBody City city) {
int count = 0;
try {
count = iCityService.insertOrUpdate(city) ? 1 : 0;
} catch (Exception e) {
logger.error("citySave -=- {}",e.toString());
}
return count;
}
/**
* 根据id删除对象
* @param id 实体ID
* @return 0 失败 1 成功
*/
@ResponseBody
@RequestMapping(method= RequestMethod.POST,value="/cityDelete")
public int cityDelete(@RequestParam(required = true) Long id){
int count = 0;
try {
count = iCityService.deleteById(id) ? 1 : 0;
}catch (Exception e){
logger.error("cityDelete -=- {}",e.toString());
}
return count;
}
/**
* 批量删除对象
* @param item 实体集合ID
* @return 0 失败 1 成功
*/
@ResponseBody
@RequestMapping(method= RequestMethod.POST,value="/cityBatchDelete")
public int deleteBatchIds(@RequestParam(required = true) List<Long> ids){
int count = 0;
try {
count = iCityService.deleteBatchIds(ids) ? 1 : 0;
}catch (Exception e){
logger.error("cityBatchDelete -=- {}",e.toString());
}
return count;
}
}