周娟优秀作者
原创内容 来源:小居数码网 时间:2024-07-30 19:38:01 阅读() 收藏:32 分享:63 爆
导读:您正在阅读的是关于【数码知识】的问题,本文由科普作家协会,生活小能手,著名生活达人等整理监督编写。本文有6987个文字,大小约为22KB,预计阅读时间18分钟。
MyBatis-Plus自定义代码生成模板工具解析最近公司要求开发自定义ORM映射框架,支持DM8达梦数据库、MySQL、Oracle等数据库,本文就Spring Boot自定义MyBatis-Plus生成MySQL数据库进行列举说明,方便大家参考。可实现自定义Controller、实体类等工具。
手动添加相关坐标依赖:
<!-- mybatis代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>
<!-- mybatis核心代码 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>3.4.0</version>
</dependency>
<!-- 数据库连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- 自定义模版引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<!-- java模版引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.opendi.entity
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 2
#驼峰下划线转换
db-column-underline: true
#刷新mapper 调试神器
refresh-mapper: true
#数据库大写下划线转换
#capital-mode: true
#序列接口实现类配置
#key-generator: com.baomidou.springboot.xxx
#逻辑删除配置
#logic-delete-value: 0
#logic-not-delete-value: 1
#自定义填充策略接口实现
#meta-object-handler: com.baomidou.springboot.MyMetaObjectHandler
#自定义SQL注入器
#sql-injector: com.baomidou.springboot.xxx
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
#不加这个查询数据为空时,字段将被隐藏
call-setters-on-nulls: true
@EnableTransactionManagement
@Configuration
@MapperScan("com.opendi.mapper*")
@Slf4j
public class MybatisOpenDiPlusConfig {
/**
* mybatis-plus SQL执行效率插件
*/
@Bean
@Profile({"dev","test","uat"})// 设置 dev test uat环境开启
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
/*<!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 -->*/
//performanceInterceptor.setMaxTime(1000);
/*<!--SQL是否格式化 默认false-->*/
//performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
/**
* mybatis-plus分页插件<br>
* 文档:http://mp.baomidou.com<br>
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationHxdiInterceptor = new PaginationInterceptor();
paginationHxdiInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
return paginationHxdiInterceptor;
}
}
@Slf4j
public class OcdiGenerator {
// 运行主工具
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Veloctiy
// mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("F://ocdi//");
gc.setFileOverride(true);
gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
//gc.setKotlin(true);//是否生成 kotlin 代码
gc.setAuthor("Java功夫");
// 自定义文件命名,注意 %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("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("ocdi");
dsc.setUrl("jdbc:mysql://192.168.3.5:3306/ocr-sba?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[] { "app_certificate" }); // 需要生成的表
// strategy.setExclude(new String[]{"test"}); // 排除生成的表
// 自定义实体父类
// strategy.setSuperEntityClass("com.ocdi.demo.TestEntity");
// 自定义实体,公共字段
// strategy.setSuperEntityColumns(new String[] { "create_date", "update_date" });
// 自定义 mapper 父类
// strategy.setSuperMapperClass("com.ocdi.demo.TestMapper");
// 自定义 service 父类
// strategy.setSuperServiceClass("com.ocdi.demo.TestService");
// 自定义 service 实现类父类
// strategy.setSuperServiceImplClass("com.ocdi.demo.TestServiceImpl");
// 自定义 controller 父类
// strategy.setSuperControllerClass("com.ocdi.demo.TestController");
// 【实体】是否生成字段常量(默认 false)
// public static final String ID = "test_id";
strategy.setEntityColumnConstant(true);
// 【实体】是否为构建者模型(默认 false)
// public User setName(String name) {this.name = name; return this;}
//strategy.setEntityBuilderModel(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.opendi");
pc.setController("controller");
pc.setEntity("model");
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("dce", 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 "F://ocdi//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 "F://ocdi//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 "F://ocdi//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("/templatesMybatis/entity.java.vm");
tc.setMapper("/templatesMybatis/mapper.java.vm");
tc.setXml("/templatesMybatis/mapper.xml.vm");
// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
// 打印注入设置【可无】
log.info(mpg.getCfg().getMap().get("dce"));
}
}
自定义controller模板文件 com
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..constant.Constant;
import com.opendi.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){
log.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){
log.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) {
log.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){
log.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){
log.error("${table.entityPath}BatchDelete -=- {}",e.toString());
}
return count;
}
}
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}> {#elsepublic 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#endprivate ${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}) {#elsepublic void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {#endthis.${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})@Overrideprotected Serializable pkVal() {#if(${keyPropertyName})return this.${keyPropertyName};#elsereturn this.id;#end}
#end#if(!${entityLombokModel})@Overridepublic String toString() {return "${entity}{" +#foreach($field in ${table.fields})#if($!{velocityCount}==1)"${field.propertyName}=" + ${field.propertyName} +#else", ${field.propertyName}=" + ${field.propertyName} +#end#end"}";}#end}
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}> {
}
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 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>#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>
package ${package.Service};
import com.baomidou.mybatisplus.plugins.Page;import ${package.Entity}.${entity};import ${superServiceClassPackage};import com.opendi.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<HxdiType> selectList(${entity} ${table.entityPath});}
package ${package.ServiceImpl};
import com.baomidou.mybatisplus.mapper.EntityWrapper;import com.baomidou.mybatisplus.plugins.Page;import com.opendi.model.BootStrapTable;import ${package.Entity}.${entity};import ${package.Mapper}.${table.mapperName};import ${package.Service}.${table.serviceName};import ${superServiceImplClassPackage};import org.springframework.stereotype.Service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.transaction.annotation.Transactional;import com.opendi.utils.lang.StringUtils;
import java.util.List;/*** <p>* $!{table.comment} 服务实现类* </p>** @author ${author}* @since ${date}*/@Service@Transactionalpublic class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
@Autowiredprivate ${table.mapperName} ${table.entityPath}Mapper;
@Overridepublic Page<${entity}> selectPage(BootStrapTable<${entity}> bootStrapTable, ${entity} ${table.entityPath}) {EntityWrapper<${entity}> entityWrapper = new EntityWrapper<${entity}>();getEntityWrapper(entityWrapper,${table.entityPath});return super.selectPage(bootStrapTable.getPagePlus(),entityWrapper);}
@Overridepublic List<${entity}> selectList(${entity} ${table.entityPath}) {EntityWrapper<${entity}> entityWrapper = new EntityWrapper<${entity}>();getEntityWrapper(entityWrapper,${table.entityPath});return super.selectList(entityWrapper);}
/*** 公共查询条件* @param entityWrapper* @return*/public EntityWrapper<${entity}> getEntityWrapper(EntityWrapper<${entity}> entityWrapper,${entity} ${table.entityPath}){//条件拼接#foreach($field in ${table.fields})#if(!${field.keyFlag})if (StringUtils.isNotBlank(${table.entityPath}.${getprefix}${field.capitalName}())){entityWrapper.like(${entity}.${field.name.toUpperCase()},${table.entityPath}.${getprefix}${field.capitalName}());}#end#endreturn entityWrapper;}}
html 页面代码生成器 前端页面使用super ui 可自行修改 基本语法一样的
默认都不能为空,生成之后 自行删减
<!DOCTYPE html><html lang="en" xmlns="http://ment}</label><div><input name="${field.propertyName}" value=""/></div></div>#end#end
<div><label></label><div><button type="submit"><i></i> 保存</button><button type="button" οnclick="layer_close();"><iclass="fa fa-close"></i> 关闭</button></div></div></div></form></div></section></body><div th:replace="common/common_foot :: foot"></div><script th:src="@{/content/plugins/jquery.validation/jquery.validate.js}"></script><script th:src="@{/content/plugins/jquery.validation/validate-methods.js}"></script><script th:src="@{/content/common/validation/common.validation.js}"></script><script th:inline="javascript">#macro(dian).#end #set($bootstrapTable = '$table')
$(function () {$(".select2").select2({placeholder: "请选择",width: "100%" //设置下拉框的宽度});$('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({checkboxClass: 'icheckbox_square-blue',radioClass: 'iradio_square-blue',increaseArea: '20%' // optional});$("#form-admin-add").validate({rules: {#foreach($field in ${table.fields})#if(!${field.keyFlag})##生成普通字段${field.propertyName}: {required: true}#if(${table.fields.size()} != ${velocityCount}),#end#end#end},onkeyup: false,submitHandler: function (form) {$.ajax({url: getRootPath()+"/a/${table.entityPath}/${table.entityPath}Save",type: "Post",dataType: "json",data: $(form).serialize(),success: function (result) {if (result > 0) {opaler();} else {opalerNO();}//刷新父级页面parent.$bootstrapTable#dian()bootstrapTable('refresh'); //再刷新DT}});}});});</script></html>
上面就是小居数码小编今天给大家介绍的关于(mybatis-plus自动生成代码)的全部内容,希望可以帮助到你,想了解更多关于数码知识的问题,欢迎关注我们,并收藏,转发,分享。
94%的朋友还想知道的:
(507)个朋友认为回复得到帮助。
部分文章信息来源于以及网友投稿,转载请说明出处。
本文标题:mybatisplus代码生成器使用(mybatis-plus自动生成代码):http://sjzlt.cn/shuma/153028.html