mybatis-generator自定义swagger-doc插件扩展


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.chenshang.plugin</groupId>
  <artifactId>mybatis-swagger</artifactId>
  <version>1.0-SNAPSHOT</version>

  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.3.7</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>8</source>
          <target>8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

java

package com.chenshang.plugin;

import java.util.List;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.Plugin;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;

public class MybatisSwaggerDoc extends PluginAdapter {

  @Override
  public boolean validate(List<String> warnings) {
    return true;
  }

  @Override
  public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, Plugin.ModelClassType modelClassType) {
    String classAnnotation = "@ApiModel(value=\"" + topLevelClass.getType().getShortName() + "\")";
    if (!topLevelClass.getAnnotations().contains(classAnnotation)) {
      topLevelClass.addAnnotation(classAnnotation);
    }

    String apiModelAnnotationPackage = properties.getProperty("apiModelAnnotationPackage");
    String apiModelPropertyAnnotationPackage = properties.getProperty("apiModelPropertyAnnotationPackage");
    if (null == apiModelAnnotationPackage) {
      apiModelAnnotationPackage = "io.swagger.annotations.ApiModel";
    }
    if (null == apiModelPropertyAnnotationPackage) {
      apiModelPropertyAnnotationPackage = "io.swagger.annotations.ApiModelProperty";
    }

    topLevelClass.addImportedType(apiModelAnnotationPackage);
    topLevelClass.addImportedType(apiModelPropertyAnnotationPackage);

    field.addAnnotation("@ApiModelProperty(value=\"" + introspectedColumn.getRemarks() +
      "\",name=\"" + introspectedColumn.getJavaProperty() +
      "\",dataType=\"" + introspectedColumn.getFullyQualifiedJavaType().getShortName() +
      "\")");
    return super.modelFieldGenerated(field, topLevelClass, introspectedColumn, introspectedTable, modelClassType);
  }
}

评论