Mybatis-generator 自定义插件具体生成代码

 

在使用mybatis-generator 自动生成代码是带selective的方法针对字符串类型的字段,只做了判空的处理,并没有对 ' ' 进行判断

<if test="record.updateBy != null">
      update_by = #{record.updateBy,jdbcType=VARCHAR},
 </if>

我需要的应该是这种

<if test="record.updateBy != null and record.updateBy != ''">
      update_by = #{record.updateBy,jdbcType=VARCHAR},
 </if>

可以通过继承PluginAdapter类重写对应的方法来进行更改对应代码生成逻辑

package com.fawkes.hsgf.common.config;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Element;
import org.mybatis.generator.api.dom.xml.XmlElement;

import java.util.List;

public class CustomUpdatePlugin extends PluginAdapter {

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

    @Override
    public boolean sqlMapInsertSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        processSelectiveElement(element, introspectedTable, false);
        return true;
    }

    @Override
    public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        processSelectiveElement(element, introspectedTable, false);
        return true;
    }

    @Override
    public boolean sqlMapUpdateByExampleSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        processSelectiveElement(element, introspectedTable, true);
        return true;
    }

    private void processSelectiveElement(XmlElement element, IntrospectedTable introspectedTable, boolean isExampleMethod) {
        for (Element e : element.getElements()) {
            if (e instanceof XmlElement) {
                XmlElement xmlElement = (XmlElement) e;

                // 处理<set>或<trim>标签中的内容
                if ("set".equals(xmlElement.getName()) || "trim".equals(xmlElement.getName())) {
                    processSetElement(xmlElement, introspectedTable, isExampleMethod);
                }
            }
        }
    }

    private void processSetElement(XmlElement setElement, IntrospectedTable introspectedTable, boolean isExampleMethod) {
        for (Element subElement : setElement.getElements()) {
            if (subElement instanceof XmlElement) {
                XmlElement ifElement = (XmlElement) subElement;

                if ("if".equals(ifElement.getName())) {
                    Attribute testAttribute = ifElement.getAttributes().get(0);
                    String testValue = testAttribute.getValue();

                    if (testValue.contains(" != null")) {
                        // 提取字段名
                        String fieldName = extractFieldNameFromTestValue(testValue, isExampleMethod);

                        // 将字段名转换为下划线格式
                        String underlinedFieldName = camelToUnderline(fieldName);

                        // 获取对应的数据库字段
                        IntrospectedColumn column = introspectedTable.getColumn(underlinedFieldName);
                        if (column != null && isStringJdbcType(column)) {
                            String newTestValue;
                            // 如果是带有 Example 的方法,添加 record. 前缀
                            if (isExampleMethod) {
                                newTestValue = testValue + " and record." + fieldName + " != ''";
                            } else {
                                newTestValue = testValue + " and " + fieldName + " != ''";
                            }
                            // 更新<if>标签的test属性
                            ifElement.getAttributes().clear();
                            ifElement.addAttribute(new Attribute("test", newTestValue));
                        }
                    }
                }
            }
        }
    }

    private boolean isStringJdbcType(IntrospectedColumn column) {
        String jdbcType = column.getJdbcTypeName();
        return "VARCHAR".equals(jdbcType) || "CHAR".equals(jdbcType) || "LONGVARCHAR".equals(jdbcType);
    }

    private String extractFieldNameFromTestValue(String testAttributeValue, boolean isExampleMethod) {
        int endIndex = testAttributeValue.indexOf(" != null");
        String trim = testAttributeValue.substring(0, endIndex).trim();
        if (isExampleMethod) {
            trim = trim.substring(7, trim.length()).trim();
        }
        return trim;
    }

    private String camelToUnderline(String camelStr) {
        StringBuilder result = new StringBuilder();
        if (camelStr != null && camelStr.length() > 0) {
            result.append(Character.toLowerCase(camelStr.charAt(0)));
            for (int i = 1; i < camelStr.length(); i++) {
                char ch = camelStr.charAt(i);
                if (Character.isUpperCase(ch)) {
                    result.append('_').append(Character.toLowerCase(ch));
                } else {
                    result.append(ch);
                }
            }
        }
        return result.toString();
    }
}

还需要将自定义插件类引入到generatorConfig.xml文件中

最后通过 MyBatisGenerator.generate方法来生成代码的,如果你使用maven插件的话,会一直报无法实例化你自定义的插件类,好像是因为通过maven插件执行时,classpath不同导致的

public class Generator {
public static void main(String[] args) {
List<String> warnings = new ArrayList<>();
boolean overwrite = true;
File configFile = new File("src/main/resources/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config;
try {
config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (Exception e) {
e.printStackTrace();
}
}

}

 

posted @ 2024-08-21 17:04  不想被举的栗子  阅读(0)  评论(0编辑  收藏  举报