Skip to content

Commit

Permalink
feat: add mebatis generator (#873)
Browse files Browse the repository at this point in the history
* feat: add prometheus-trace-etl release

* feat: add gitlab log release jdk21

* feat: update athena

* feat: update check code file path

* feat: add code generator and mybatis generator

* feat: add mybtais generator
  • Loading branch information
sadadw1 authored Aug 15, 2024
1 parent 7462e38 commit 2d55920
Show file tree
Hide file tree
Showing 9 changed files with 231 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package com.xiaomi.youpin.codegen;

import com.xiaomi.youpin.codegen.bo.Dependency;
import com.xiaomi.youpin.codegen.common.FileUtils;
import com.xiaomi.youpin.codegen.generator.FileGenerator;
import com.xiaomi.youpin.infra.rpc.Result;
import com.xiaomi.youpin.infra.rpc.errors.GeneralCodes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class M78DoceanMongoGen {
// private static final String DEFAULT_MODEL = "mi-function";
private final String tmpPath = "m78-docean-mongo";
// private static final String handlerDir = "handler";
// private static final String srcPath = "/src/main/java/";
// private static final String testPath = "/src/test/java/";

public Result<String> generateAndZip(String projectPath, String projectName, String groupId, String packageName, String author, String versionId, HashMap<String, ArrayList<Dependency>> dep) {
String packagePath = packageName.replaceAll("\\.", "/");
String camelName = this.adapterProjectNameToCamelName(projectName);
Map<String, Object> m = new HashMap<>();
m.put("group", groupId);
m.put("artifactId", projectName);
m.put("version", versionId);
m.put("author", author);
m.put("camelName", camelName);
m.put("package", packageName);
try {
// FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-common", "src", "test", "java"));
FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-server", "src", "main", "java", packagePath, "bootstrap"));
FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-server", "src", "test", "java"));
FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-service", "src", "test", "java"));
// FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-service", "src", "main", "resources"));
FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-api", "src", "main", "java", packagePath, "api", "bo"));
FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-api", "src", "main", "java", packagePath, "api", "vo"));
FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-server", "src", "main", "java", packagePath, "controller"));
FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-common", "src", "main", "java", packagePath, "common"));
FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-server", "src", "main", "resources", "config"));
FileUtils.createDirectories(FileUtils.join(projectPath, projectName, projectName + "-service", "src", "main", "java", packagePath, "service"));
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-service", "src", "main", "java", packagePath, "service", "MongoService.java"), FileUtils.join(tmpPath, "mongoservice.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-api", "src", "main", "java", packagePath, "api", "bo", "MongoBo.java"), FileUtils.join(tmpPath, "mongobo.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-api", "src", "main", "java", packagePath, "api", "bo", "Page.java"), FileUtils.join(tmpPath, "page.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-service", "pom.xml"), FileUtils.join(tmpPath, "service-pom.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-service", "src", "main", "java", packagePath, "service", "ServiceImpl1.java"), FileUtils.join(tmpPath, "serviceimpl1.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-server", "src", "main", "resources", "config", "staging.properties"), FileUtils.join(tmpPath, "staging.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-server", "src", "main", "resources", "config.properties"), FileUtils.join(tmpPath, "config.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-server", "src", "main", "resources", "logback.xml"), FileUtils.join(tmpPath, "logback.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join("pom.xml"), FileUtils.join(tmpPath, "pom.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-common", "src", "main", "java", packagePath, "common", "Result.java"), FileUtils.join(tmpPath, "result.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-server", "src", "main", "java", packagePath, "bootstrap", "Bootstrap.java"), FileUtils.join(tmpPath, "bootstrap.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-server", "src", "main", "java", packagePath, "controller", "MongodbController.java"), FileUtils.join(tmpPath, "mongodbcontroller.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-server", "pom.xml"), FileUtils.join(tmpPath, "server-pom.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-server", "src", "main", "resources", "config", "dev.properties"), FileUtils.join(tmpPath, "dev.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-server", "src", "main", "resources", "config", "online.properties"), FileUtils.join(tmpPath, "online.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-api", "pom.xml"), FileUtils.join(tmpPath, "api-pom.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-api", "src", "main", "java", packagePath, "api", "IService.java"), FileUtils.join(tmpPath, "iservice.tml")).generator(m);
new FileGenerator(projectPath, projectName, FileUtils.join(projectName + "-common", "pom.xml"), FileUtils.join(tmpPath, "common-pom.tml")).generator(m);

new FileGenerator(projectPath, projectName, FileUtils.join(".gitignore"), "springboot_gitignore.tml").generator(m);
FileUtils.compress(projectPath + File.separator + projectName, projectPath + File.separator + projectName + ".zip");
} catch (Exception e) {
log.error("SpringBootProGen failed ", e);
return Result.fail(GeneralCodes.InternalError, "InternalError");
}

return Result.success(projectPath + File.separator + projectName + ".zip");
}

private String adapterProjectNameToCamelName(String name) {
if (StringUtils.isEmpty(name)) {
return "";
}
try {
String[] strings = name.split("-");
if (strings.length > 1) {
String res = "";
for (int i = 0; i < strings.length; i++) {
if (!StringUtils.isEmpty(strings[i])) {
res = res + StringUtils.capitalize(strings[i]);
}
}
return res;
}
} catch (Exception e) {
return StringUtils.capitalize(name);
}
return StringUtils.capitalize(name);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@
*/
public class FileUtils {

public static String join(String... ps) {
return String.join(File.separator, ps);
}

public static void createDirectories(String path) {
try {
Files.createDirectories(Paths.get(path));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package run.mone.ai.codegen;

import com.google.gson.Gson;
import com.mybatisflex.codegen.Generator;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.zaxxer.hikari.HikariDataSource;
Expand All @@ -10,6 +11,7 @@
import run.mone.ai.codegen.bo.FeatureGenerateBo;
import run.mone.ai.codegen.util.TemplateUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
Expand All @@ -21,6 +23,17 @@
@Slf4j
public class FeatureGenerator {

private static final Gson gson = new Gson();

public static void main(String[] args) {
FeatureGenerateBo featureGenerateBo = null;
//方便ai调用的时候,设置表名
if (args.length > 0) {
featureGenerateBo = parseArgsAndExtractData(args);
generateWithTemplate(featureGenerateBo);
}
}

public static void generateWithTemplate(FeatureGenerateBo featureGenerateBo) {

// 类型检查
Expand Down Expand Up @@ -147,4 +160,15 @@ public static String replaceDotWithSlash(String input) {
}
return input.replace(".", "/");
}

private static FeatureGenerateBo parseArgsAndExtractData(String[] args) {
String jsonStr = args[0];

jsonStr = new String(Base64.getDecoder().decode(jsonStr));
log.info("jsonStr:{}", jsonStr);

FeatureGenerateBo bo = gson.fromJson(jsonStr, FeatureGenerateBo.class);
log.info("map:{}", bo);
return bo;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import org.mybatis.generator.config.TableConfiguration;
import org.mybatis.generator.internal.DefaultShellCallback;
import run.mone.ai.codegen.bo.FeatureGenerateBo;
import run.mone.ai.codegen.bo.MybatisGeneratorResult;
import run.mone.ai.codegen.holder.MybatisGeneratorHolder;

import java.util.ArrayList;
import java.util.Base64;
Expand All @@ -31,19 +33,19 @@ public static void main(String[] args) {
//方便ai调用的时候,设置表名
if (args.length > 0) {
featureGenerateBo = parseArgsAndExtractData(args);
generateMyBatisFiles(featureGenerateBo);
}
generateMyBatisFiles(featureGenerateBo);
}

// 使用mybatis-generator生成指定表对应的XML、Mapper和Entity类
public static void generateMyBatisFiles(FeatureGenerateBo featureGenerateBo) {
public static MybatisGeneratorResult generateMyBatisFiles(FeatureGenerateBo featureGenerateBo) {
MybatisGeneratorResult result = new MybatisGeneratorResult();
if (Objects.isNull(featureGenerateBo.getTableName())) {
log.warn("Table name is empty, cannot generate MyBatis files!");
return;
return result;
}
// 配置MyBatis Generator
List<String> warnings = new ArrayList<>();
boolean overwrite = true;
Configuration config = new Configuration();

Context context = new Context(ModelType.FLAT);
Expand All @@ -60,7 +62,7 @@ public static void generateMyBatisFiles(FeatureGenerateBo featureGenerateBo) {

// 配置Java模型生成器
JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
javaModelGeneratorConfiguration.setTargetPackage(featureGenerateBo.getMybatisDaoPath());
javaModelGeneratorConfiguration.setTargetPackage(featureGenerateBo.getMybatisEntityPath());
javaModelGeneratorConfiguration.setTargetProject(featureGenerateBo.getMybatisDaoModule() + "/src/main/java");
context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);

Expand Down Expand Up @@ -100,20 +102,37 @@ public static void generateMyBatisFiles(FeatureGenerateBo featureGenerateBo) {
removeGetSetMethodsPlugin.setConfigurationType("run.mone.ai.codegen.plugin.RemoveGetSetMethodsPlugin");
context.addPluginConfiguration(removeGetSetMethodsPlugin);

if(!featureGenerateBo.isOverwrite()) {
// 使得xml文件不会被覆盖
PluginConfiguration unmergeXML = new PluginConfiguration();
unmergeXML.setConfigurationType("org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin");
context.addPluginConfiguration(unmergeXML);
}

// 存储这次生成的类名,以便返回
PluginConfiguration classNamePlugin = new PluginConfiguration();
classNamePlugin.setConfigurationType("run.mone.ai.codegen.plugin.ClassNamePlugin");
context.addPluginConfiguration(classNamePlugin);

config.addContext(context);

DefaultShellCallback callback = new DefaultShellCallback(overwrite);
DefaultShellCallback callback = new DefaultShellCallback(featureGenerateBo.isOverwrite());
MyBatisGenerator myBatisGenerator;
try {
myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);

// 获取返回结果
result.setEntity(MybatisGeneratorHolder.entity);
result.setMapper(MybatisGeneratorHolder.mapper);
} catch (Exception e) {
log.error("Error generating MyBatis files", e);
}

if (!warnings.isEmpty()) {
warnings.forEach(log::warn);
}
return result;
}

private static FeatureGenerateBo parseArgsAndExtractData(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,10 @@ public class FeatureGenerateBo {
@Builder.Default
private String mybatisEntityPath = "";

/**
* mybatis 是否覆盖现有类,默认不覆盖,如果存在现有类则跳过
*/
@Builder.Default
private boolean overwrite = false;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package run.mone.ai.codegen.bo;

import lombok.Data;
import lombok.ToString;


@Data
@ToString
public class MybatisGeneratorResult {
/**
* 生成的Java Entity类列表
*/
private String entity;

/**
* 生成的Java mapper类列表
*/
private String mapper;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package run.mone.ai.codegen.holder;

import lombok.Data;

public class MybatisGeneratorHolder {

public static String entity;
public static String mapper;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package run.mone.ai.codegen.plugin;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.config.Context;
import run.mone.ai.codegen.holder.MybatisGeneratorHolder;
import org.mybatis.generator.api.JavaFormatter;

import java.util.List;

public class ClassNamePlugin extends PluginAdapter {

private JavaFormatter javaFormatter;

@Override
public void setContext(Context context) {
super.setContext(context);
this.javaFormatter = context.getJavaFormatter();
}

@Override
public boolean validate(List<String> warnings) {
// 这里可以添加一些验证逻辑
return true;
}

@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
String formattedContent = javaFormatter.getFormattedContent(topLevelClass);
MybatisGeneratorHolder.entity = formattedContent;
return true;
}


@Override
public boolean clientGenerated(Interface interfaze, IntrospectedTable introspectedTable) {
String formattedContent = javaFormatter.getFormattedContent(interfaze);
MybatisGeneratorHolder.mapper = formattedContent;
return true;
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import run.mone.ai.codegen.MybatisGenerator;
import run.mone.ai.codegen.bo.FeatureGeneratType;
import run.mone.ai.codegen.bo.FeatureGenerateBo;
import run.mone.ai.codegen.bo.MybatisGeneratorResult;

public class FeatureGeneratorTest {

Expand Down Expand Up @@ -38,12 +39,13 @@ public void testGenerateWithMybatis() {
featureGenerateBo.setPassword(dbPwd);
featureGenerateBo.setTableName("user");

featureGenerateBo.setMybatisDaoModule("/your/path/mone/jcommon/codegen");
featureGenerateBo.setMybatisDaoModule("/your path/mone/jcommon/codegen");
featureGenerateBo.setMybatisXMLPath("com.xiaomi.dao.mapper");
featureGenerateBo.setMybatisDaoPath("com.xiaomi.dao.mapper");
featureGenerateBo.setMybatisEntityPath("com.xiaomi.dao.entity");

MybatisGenerator.generateMyBatisFiles(featureGenerateBo);
MybatisGeneratorResult mybatisGeneratorResult = MybatisGenerator.generateMyBatisFiles(featureGenerateBo);
System.out.println(mybatisGeneratorResult);
}

}

0 comments on commit 2d55920

Please sign in to comment.