Browse Source

修改mapper.xml文件生成格式-->实现jdbcType无须手动修改

pull/1/head
yanshaoshuai 4 years ago
parent
commit
4c2e51d018
9 changed files with 136 additions and 36 deletions
  1. +0
    -7
      spring-boot-demo-codegen/pom.xml
  2. +4
    -0
      spring-boot-demo-codegen/src/main/java/com/xkcoding/codegen/entity/ColumnEntity.java
  3. +13
    -9
      spring-boot-demo-codegen/src/main/java/com/xkcoding/codegen/utils/CodeGenUtil.java
  4. +21
    -0
      spring-boot-demo-codegen/src/main/resources/jdbc_type.properties
  5. +79
    -0
      spring-boot-demo-codegen/src/main/resources/logback-spring.xml
  6. +11
    -15
      spring-boot-demo-codegen/src/main/resources/template/Controller.java.vm
  7. +4
    -2
      spring-boot-demo-codegen/src/main/resources/template/Entity.java.vm
  8. +2
    -2
      spring-boot-demo-codegen/src/main/resources/template/Mapper.xml.vm
  9. +2
    -1
      spring-boot-demo-codegen/src/main/resources/template/ServiceImpl.java.vm

+ 0
- 7
spring-boot-demo-codegen/pom.xml View File

@@ -9,13 +9,6 @@


<name>spring-boot-demo-codegen</name> <name>spring-boot-demo-codegen</name>
<description>Demo project for Spring Boot</description> <description>Demo project for Spring Boot</description>

<parent>
<groupId>com.xkcoding</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>

<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>


+ 4
- 0
spring-boot-demo-codegen/src/main/java/com/xkcoding/codegen/entity/ColumnEntity.java View File

@@ -42,6 +42,10 @@ public class ColumnEntity {
*/ */
private String attrType; private String attrType;
/** /**
* jdbc类型
*/
private String jdbcType;
/**
* 其他信息 * 其他信息
*/ */
private String extra; private String extra;


+ 13
- 9
spring-boot-demo-codegen/src/main/java/com/xkcoding/codegen/utils/CodeGenUtil.java View File

@@ -69,7 +69,9 @@ public class CodeGenUtil {
*/ */
public void generatorCode(GenConfig genConfig, Entity table, List<Entity> columns, ZipOutputStream zip) { public void generatorCode(GenConfig genConfig, Entity table, List<Entity> columns, ZipOutputStream zip) {
//配置信息 //配置信息
Props props = getConfig();
Props propsDB2Java = getConfig("generator.properties");
Props propsDB2Jdbc = getConfig("jdbc_type.properties");

boolean hasBigDecimal = false; boolean hasBigDecimal = false;
//表信息 //表信息
TableEntity tableEntity = new TableEntity(); TableEntity tableEntity = new TableEntity();
@@ -85,7 +87,7 @@ public class CodeGenUtil {
if (StrUtil.isNotBlank(genConfig.getTablePrefix())) { if (StrUtil.isNotBlank(genConfig.getTablePrefix())) {
tablePrefix = genConfig.getTablePrefix(); tablePrefix = genConfig.getTablePrefix();
} else { } else {
tablePrefix = props.getStr("tablePrefix");
tablePrefix = propsDB2Java.getStr("tablePrefix");
} }


//表名转换成Java类名 //表名转换成Java类名
@@ -108,8 +110,10 @@ public class CodeGenUtil {
columnEntity.setLowerAttrName(StrUtil.lowerFirst(attrName)); columnEntity.setLowerAttrName(StrUtil.lowerFirst(attrName));


//列的数据类型,转换成Java类型 //列的数据类型,转换成Java类型
String attrType = props.getStr(columnEntity.getDataType(), "unknownType");
String attrType = propsDB2Java.getStr(columnEntity.getDataType(), "unknownType");
columnEntity.setAttrType(attrType); columnEntity.setAttrType(attrType);
String jdbcType = propsDB2Jdbc.getStr(columnEntity.getDataType(), "unknownType");
columnEntity.setJdbcType(jdbcType);
if (!hasBigDecimal && "BigDecimal".equals(attrType)) { if (!hasBigDecimal && "BigDecimal".equals(attrType)) {
hasBigDecimal = true; hasBigDecimal = true;
} }
@@ -152,21 +156,21 @@ public class CodeGenUtil {
if (StrUtil.isNotBlank(genConfig.getAuthor())) { if (StrUtil.isNotBlank(genConfig.getAuthor())) {
map.put("author", genConfig.getAuthor()); map.put("author", genConfig.getAuthor());
} else { } else {
map.put("author", props.getStr("author"));
map.put("author", propsDB2Java.getStr("author"));
} }


if (StrUtil.isNotBlank(genConfig.getModuleName())) { if (StrUtil.isNotBlank(genConfig.getModuleName())) {
map.put("moduleName", genConfig.getModuleName()); map.put("moduleName", genConfig.getModuleName());
} else { } else {
map.put("moduleName", props.getStr("moduleName"));
map.put("moduleName", propsDB2Java.getStr("moduleName"));
} }


if (StrUtil.isNotBlank(genConfig.getPackageName())) { if (StrUtil.isNotBlank(genConfig.getPackageName())) {
map.put("package", genConfig.getPackageName()); map.put("package", genConfig.getPackageName());
map.put("mainPath", genConfig.getPackageName()); map.put("mainPath", genConfig.getPackageName());
} else { } else {
map.put("package", props.getStr("package"));
map.put("mainPath", props.getStr("mainPath"));
map.put("package", propsDB2Java.getStr("package"));
map.put("mainPath", propsDB2Java.getStr("mainPath"));
} }
VelocityContext context = new VelocityContext(map); VelocityContext context = new VelocityContext(map);


@@ -213,8 +217,8 @@ public class CodeGenUtil {
/** /**
* 获取配置信息 * 获取配置信息
*/ */
private Props getConfig() {
Props props = new Props("generator.properties");
private Props getConfig(String fileName) {
Props props = new Props(fileName);
props.autoLoad(true); props.autoLoad(true);
return props; return props;
} }


+ 21
- 0
spring-boot-demo-codegen/src/main/resources/jdbc_type.properties View File

@@ -0,0 +1,21 @@
tinyint=TINYINT
smallint=SMALLINT
mediumint=MEDIUMINT
int=INTEGER
integer=INTEGER
bigint=BIGINT
float=FLOAT
double=DOUBLE
decimal=DECIMAL
bit=BIT
char=CHAR
varchar=VARCHAR
tinytext=VARCHAR
text=VARCHAR
mediumtext=VARCHAR
longtext=VARCHAR
date=DATE
datetime=DATETIME
timestamp=TIMESTAMP
blob=BLOB
longblob=LONGBLOB

+ 79
- 0
spring-boot-demo-codegen/src/main/resources/logback-spring.xml View File

@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="FILE_ERROR_PATTERN"
value="${FILE_LOG_PATTERN:-%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} %file:%line: %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>

<appender name="FILE_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--如果只是想要 Info 级别的日志,只是过滤 info 还是会输出 Error 日志,因为 Error 的级别高, 所以我们使用下面的策略,可以避免输出 Error 的日志-->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!--过滤 Error-->
<level>ERROR</level>
<!--匹配到就禁止-->
<onMatch>DENY</onMatch>
<!--没有匹配到就允许-->
<onMismatch>ACCEPT</onMismatch>
</filter>
<!--日志名称,如果没有File 属性,那么只会使用FileNamePattern的文件路径规则如果同时有<File>和<FileNamePattern>,那么当天日志是<File>,明天会自动把今天的日志改名为今天的日期。即,<File> 的日志都是当天的。-->
<!--<File>logs/info.spring-boot-demo-logback.log</File>-->
<!--滚动策略,按照时间滚动 TimeBasedRollingPolicy-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--文件路径,定义了日志的切分方式——把每一天的日志归档到一个文件中,以防止日志填满整个磁盘空间-->
<FileNamePattern>logs/spring-boot-demo-logback/info.created_on_%d{yyyy-MM-dd}.part_%i.log</FileNamePattern>
<!--只保留最近90天的日志-->
<maxHistory>90</maxHistory>
<!--用来指定日志文件的上限大小,那么到了这个值,就会删除旧的日志-->
<!--<totalSizeCap>1GB</totalSizeCap>-->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- maxFileSize:这是活动文件的大小,默认值是10MB,本篇设置为1KB,只是为了演示 -->
<maxFileSize>2MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<!--<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">-->
<!--<maxFileSize>1KB</maxFileSize>-->
<!--</triggeringPolicy>-->
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
</appender>

<appender name="FILE_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--如果只是想要 Error 级别的日志,那么需要过滤一下,默认是 info 级别的,ThresholdFilter-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>Error</level>
</filter>
<!--日志名称,如果没有File 属性,那么只会使用FileNamePattern的文件路径规则如果同时有<File>和<FileNamePattern>,那么当天日志是<File>,明天会自动把今天的日志改名为今天的日期。即,<File> 的日志都是当天的。-->
<!--<File>logs/error.spring-boot-demo-logback.log</File>-->
<!--滚动策略,按照时间滚动 TimeBasedRollingPolicy-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--文件路径,定义了日志的切分方式——把每一天的日志归档到一个文件中,以防止日志填满整个磁盘空间-->
<FileNamePattern>logs/spring-boot-demo-logback/error.created_on_%d{yyyy-MM-dd}.part_%i.log</FileNamePattern>
<!--只保留最近90天的日志-->
<maxHistory>90</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- maxFileSize:这是活动文件的大小,默认值是10MB,本篇设置为1KB,只是为了演示 -->
<maxFileSize>2MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>${FILE_ERROR_PATTERN}</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
</appender>

<root level="info">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE_INFO"/>
<appender-ref ref="FILE_ERROR"/>
</root>
</configuration>

+ 11
- 15
spring-boot-demo-codegen/src/main/resources/template/Controller.java.vm View File

@@ -2,17 +2,16 @@ package ${package}.${moduleName}.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xkcoding.common.R;
import com.xkcoding.scaffold.log.annotations.ApiLog;
import ${package}.${moduleName}.common.R;
import ${package}.${moduleName}.entity.${className}; import ${package}.${moduleName}.entity.${className};
import ${package}.${moduleName}.service.${className}Service; import ${package}.${moduleName}.service.${className}Service;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
/** /**
* <p> * <p>
* ${comments} * ${comments}
@@ -26,13 +25,13 @@ import io.swagger.annotations.ApiImplicitParams;
* @version: V1.0 * @version: V1.0
* @modified: ${author} * @modified: ${author}
*/ */
@Slf4j
@RestController @RestController
@AllArgsConstructor
@RequestMapping("/${pathName}") @RequestMapping("/${pathName}")
@Api(description = "${className}Controller", tags = {"${comments}"}) @Api(description = "${className}Controller", tags = {"${comments}"})
public class ${className}Controller { public class ${className}Controller {
private final ${className}Service ${classname}Service;
@Autowired
private ${className}Service ${classname}Service;


/** /**
* 分页查询${comments} * 分页查询${comments}
@@ -47,7 +46,7 @@ public class ${className}Controller {
@ApiImplicitParam(name = "${classname}", value = "查询条件", required = true) @ApiImplicitParam(name = "${classname}", value = "查询条件", required = true)
}) })
public R list${className}(Page page, ${className} ${classname}) { public R list${className}(Page page, ${className} ${classname}) {
return new R<>(${classname}Service.page(page,Wrappers.query(${classname})));
return R.success(${classname}Service.page(page,Wrappers.query(${classname})));
} }




@@ -62,7 +61,7 @@ public class ${className}Controller {
@ApiImplicitParam(name = "${pk.lowerAttrName}", value = "主键id", required = true) @ApiImplicitParam(name = "${pk.lowerAttrName}", value = "主键id", required = true)
}) })
public R get${className}(@PathVariable("${pk.lowerAttrName}") ${pk.attrType} ${pk.lowerAttrName}){ public R get${className}(@PathVariable("${pk.lowerAttrName}") ${pk.attrType} ${pk.lowerAttrName}){
return new R<>(${classname}Service.getById(${pk.lowerAttrName}));
return R.success(${classname}Service.getById(${pk.lowerAttrName}));
} }


/** /**
@@ -70,11 +69,10 @@ public class ${className}Controller {
* @param ${classname} ${comments} * @param ${classname} ${comments}
* @return R * @return R
*/ */
@ApiLog("新增${comments}")
@PostMapping @PostMapping
@ApiOperation(value = "新增${comments}", notes = "新增${comments}") @ApiOperation(value = "新增${comments}", notes = "新增${comments}")
public R save${className}(@RequestBody ${className} ${classname}){ public R save${className}(@RequestBody ${className} ${classname}){
return new R<>(${classname}Service.save(${classname}));
return R.success(${classname}Service.save(${classname}));
} }


/** /**
@@ -83,14 +81,13 @@ public class ${className}Controller {
* @param ${classname} ${comments} * @param ${classname} ${comments}
* @return R * @return R
*/ */
@ApiLog("修改${comments}")
@PutMapping("/{${pk.lowerAttrName}}") @PutMapping("/{${pk.lowerAttrName}}")
@ApiOperation(value = "修改${comments}", notes = "修改${comments}") @ApiOperation(value = "修改${comments}", notes = "修改${comments}")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name = "${pk.lowerAttrName}", value = "主键id", required = true) @ApiImplicitParam(name = "${pk.lowerAttrName}", value = "主键id", required = true)
}) })
public R update${className}(@PathVariable ${pk.attrType} ${pk.lowerAttrName}, @RequestBody ${className} ${classname}){ public R update${className}(@PathVariable ${pk.attrType} ${pk.lowerAttrName}, @RequestBody ${className} ${classname}){
return new R<>(${classname}Service.updateById(${classname}));
return R.success(${classname}Service.updateById(${classname}));
} }


/** /**
@@ -98,14 +95,13 @@ public class ${className}Controller {
* @param ${pk.lowerAttrName} id * @param ${pk.lowerAttrName} id
* @return R * @return R
*/ */
@ApiLog("删除${comments}")
@DeleteMapping("/{${pk.lowerAttrName}}") @DeleteMapping("/{${pk.lowerAttrName}}")
@ApiOperation(value = "删除${comments}", notes = "删除${comments}") @ApiOperation(value = "删除${comments}", notes = "删除${comments}")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name = "${pk.lowerAttrName}", value = "主键id", required = true) @ApiImplicitParam(name = "${pk.lowerAttrName}", value = "主键id", required = true)
}) })
public R delete${className}(@PathVariable ${pk.attrType} ${pk.lowerAttrName}){ public R delete${className}(@PathVariable ${pk.attrType} ${pk.lowerAttrName}){
return new R<>(${classname}Service.removeById(${pk.lowerAttrName}));
return R.success(${classname}Service.removeById(${pk.lowerAttrName}));
} }


} }

+ 4
- 2
spring-boot-demo-codegen/src/main/resources/template/Entity.java.vm View File

@@ -8,9 +8,10 @@ import lombok.EqualsAndHashCode;
#if(${hasBigDecimal}) #if(${hasBigDecimal})
import java.math.BigDecimal; import java.math.BigDecimal;
#end #end
import java.io.Serializable;
import java.time.LocalDateTime; import java.time.LocalDateTime;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.NoArgsConstructor;
/** /**
* <p> * <p>
* ${comments} * ${comments}
@@ -25,6 +26,7 @@ import java.time.LocalDateTime;
* @modified: ${author} * @modified: ${author}
*/ */
@Data @Data
@NoArgsConstructor
@TableName("${tableName}") @TableName("${tableName}")
@ApiModel(description = "${comments}") @ApiModel(description = "${comments}")
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)


+ 2
- 2
spring-boot-demo-codegen/src/main/resources/template/Mapper.xml.vm View File

@@ -4,9 +4,9 @@
<resultMap id="${classname}Map" type="${package}.${moduleName}.entity.${className}"> <resultMap id="${classname}Map" type="${package}.${moduleName}.entity.${className}">
#foreach($column in $columns) #foreach($column in $columns)
#if($column.lowerAttrName==$pk.lowerAttrName) #if($column.lowerAttrName==$pk.lowerAttrName)
<id property="${pk.lowerAttrName}" jdbcType="${pk.dataType}" column="${pk.columnName}"/>
<id property="${pk.lowerAttrName}" jdbcType="${pk.jdbcType}" column="${pk.columnName}"/>
#else #else
<result property="${column.lowerAttrName}" jdbcType="${column.dataType}" column="${column.columnName}"/>
<result property="${column.lowerAttrName}" jdbcType="${column.jdbcType}" column="${column.columnName}"/>
#end #end
#end #end
</resultMap> </resultMap>


+ 2
- 1
spring-boot-demo-codegen/src/main/resources/template/ServiceImpl.java.vm View File

@@ -5,7 +5,7 @@ import ${package}.${moduleName}.entity.${className};
import ${package}.${moduleName}.mapper.${className}Mapper; import ${package}.${moduleName}.mapper.${className}Mapper;
import ${package}.${moduleName}.service.${className}Service; import ${package}.${moduleName}.service.${className}Service;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
/** /**
* <p> * <p>
* ${comments} * ${comments}
@@ -20,6 +20,7 @@ import org.springframework.stereotype.Service;
* @modified: ${author} * @modified: ${author}
*/ */
@Service @Service
@Slf4j
public class ${className}ServiceImpl extends ServiceImpl<${className}Mapper, ${className}> implements ${className}Service { public class ${className}ServiceImpl extends ServiceImpl<${className}Mapper, ${className}> implements ${className}Service {


} }

Loading…
Cancel
Save