修改bug,生成文件没有错误,但是格式还有问题

This commit is contained in:
2025-10-22 09:16:17 +08:00
parent 6e76d30bac
commit c4b3d30e42
6 changed files with 101 additions and 111 deletions

View File

@@ -307,25 +307,10 @@ public class MybatisPlusCodeGenerator implements CodeGenerator {
* 添加关联字段信息 * 添加关联字段信息
*/ */
private void addRelationFields(Map<String, Object> dataModel, TableInfo tableInfo) { private void addRelationFields(Map<String, Object> dataModel, TableInfo tableInfo) {
// 不再添加固定的关联关系字段,这些应该根据实际表结构动态生成
Map<String, Object> tableMap = (Map<String, Object>) dataModel.get("table"); Map<String, Object> tableMap = (Map<String, Object>) dataModel.get("table");
tableMap.put("oneToOneFields", new ArrayList<>());
// 添加一对一关联字段 tableMap.put("oneToManyFields", new ArrayList<>());
List<Map<String, Object>> oneToOneFields = new ArrayList<>();
Map<String, Object> userDetailsField = new HashMap<>();
userDetailsField.put("propertyName", "userDetails");
userDetailsField.put("propertyType", "UserDetails");
userDetailsField.put("comment", "用户详情(一对一)");
oneToOneFields.add(userDetailsField);
tableMap.put("oneToOneFields", oneToOneFields);
// 添加一对多关联字段
List<Map<String, Object>> oneToManyFields = new ArrayList<>();
Map<String, Object> ordersField = new HashMap<>();
ordersField.put("propertyName", "orders");
ordersField.put("propertyType", "UserOrder");
ordersField.put("comment", "用户订单(一对多)");
oneToManyFields.add(ordersField);
tableMap.put("oneToManyFields", oneToManyFields);
} }
/** /**
@@ -596,7 +581,13 @@ public class MybatisPlusCodeGenerator implements CodeGenerator {
*/ */
private void writeFileToDisK(GeneratedFile generatedFile, GenerationConfig config) { private void writeFileToDisK(GeneratedFile generatedFile, GenerationConfig config) {
try { try {
FileUtils.writeFile(generatedFile.getFilePath(), generatedFile.getContent(), config.isOverride()); // 格式化Java代码内容
String content = generatedFile.getContent();
if (generatedFile.getFilePath().endsWith(".java")) {
content = FileUtils.formatJavaCode(content);
}
FileUtils.writeFile(generatedFile.getFilePath(), content, config.isOverride());
generatedFile.setNewFile(true); generatedFile.setNewFile(true);
generatedFile.setFileSize(FileUtils.getFileSize(generatedFile.getFilePath())); generatedFile.setFileSize(FileUtils.getFileSize(generatedFile.getFilePath()));
} catch (Exception e) { } catch (Exception e) {

View File

@@ -220,34 +220,7 @@ public class FreemarkerTemplateProcessor implements TemplateEngineProcessor {
code.append(" private ").append(propertyType).append(" ").append(propertyName).append(";\n\n"); code.append(" private ").append(propertyType).append(" ").append(propertyName).append(";\n\n");
} }
// 添加关联关系字段(仅对特定实体类) // 不再添加固定的关联关系字段,这些应该根据实际表结构动态生成
if ("User".equals(entity)) {
code.append(" /**\n * 用户详情(一对一)\n */\n");
if (entityJpaModel != null && entityJpaModel) {
code.append(" @OneToOne(mappedBy = \"user\", cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n");
}
code.append(" private UserDetails userDetails;\n\n");
code.append(" /**\n * 用户订单(一对多)\n */\n");
if (entityJpaModel != null && entityJpaModel) {
code.append(" @OneToMany(mappedBy = \"user\", cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n");
}
code.append(" private List<UserOrder> orders;\n\n");
} else if ("UserDetails".equals(entity)) {
code.append(" /**\n * 关联用户(一对一)\n */\n");
if (entityJpaModel != null && entityJpaModel) {
code.append(" @OneToOne\n");
code.append(" @JoinColumn(name = \"user_id\")\n");
}
code.append(" private User user;\n\n");
} else if ("UserOrder".equals(entity)) {
code.append(" /**\n * 关联用户(多对一)\n */\n");
if (entityJpaModel != null && entityJpaModel) {
code.append(" @ManyToOne\n");
code.append(" @JoinColumn(name = \"user_id\")\n");
}
code.append(" private User user;\n\n");
}
} else { } else {
// 默认字段定义(为了兼容性) // 默认字段定义(为了兼容性)
code.append(" /**\n * 主键ID\n */\n"); code.append(" /**\n * 主键ID\n */\n");
@@ -428,7 +401,7 @@ public class FreemarkerTemplateProcessor implements TemplateEngineProcessor {
// 注解和接口声明 // 注解和接口声明
code.append("@Mapper\n"); code.append("@Mapper\n");
code.append("public interface ").append(entity).append("Mapper extends BaseMapper<").append(entity).append("> {\n\n"); code.append("public interface ").append(entity).append("Mapper extends BaseMapper<").append(entity).append("> {\n");
code.append("}\n"); code.append("}\n");
return code.toString(); return code.toString();

View File

@@ -6,79 +6,98 @@ import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.regex.Pattern;
/** /**
* 文件工具类 * 文件工具类
* *
* @author yexuejc * @author yexuejc
* @since 2025-01 * @since 2024/10/17
*/ */
public class FileUtils { public class FileUtils {
/** /**
* 写文件到磁盘 * 写文件
* *
* @param filePath 文件路径 * @param filePath 文件路径
* @param content 文件内容 * @param content 文件内容
* @param override 是否覆盖已存在文件 * @param override 是否覆盖
* @return 是否写入成功
* @throws IOException IO异常 * @throws IOException IO异常
*/ */
public static boolean writeFile(String filePath, String content, boolean override) throws IOException { public static void writeFile(String filePath, String content, boolean override) throws IOException {
File file = new File(filePath); Path path = Paths.get(filePath);
File file = path.toFile();
// 检查文件是否存在 if (!file.getParentFile().exists()) {
if (file.exists() && !override) { file.getParentFile().mkdirs();
System.out.println("文件已存在,跳过: " + filePath);
return false;
} }
// 创建父目录 if (!file.exists() || override) {
createDirectories(file.getParent()); try (FileWriter writer = new FileWriter(file)) {
writer.write(content);
// 写入文件
try (FileWriter writer = new FileWriter(file, false)) {
writer.write(content);
writer.flush();
System.out.println("成功写入文件: " + filePath);
return true;
}
}
/**
* 创建目录
*
* @param dirPath 目录路径
* @throws IOException IO异常
*/
public static void createDirectories(String dirPath) throws IOException {
if (dirPath != null && !dirPath.trim().isEmpty()) {
Path path = Paths.get(dirPath);
if (!Files.exists(path)) {
Files.createDirectories(path);
System.out.println("创建目录: " + dirPath);
} }
} }
} }
/**
* 检查文件是否存在
*
* @param filePath 文件路径
* @return 是否存在
*/
public static boolean fileExists(String filePath) {
return new File(filePath).exists();
}
/** /**
* 获取文件大小 * 获取文件大小
* *
* @param filePath 文件路径 * @param filePath 文件路径
* @return 文件大小(字节) * @return 文件大小
*/ */
public static long getFileSize(String filePath) { public static long getFileSize(String filePath) {
File file = new File(filePath); Path path = Paths.get(filePath);
return file.exists() ? file.length() : 0; try {
return Files.size(path);
} catch (IOException e) {
return -1;
}
}
/**
* 格式化Java代码内容
*
* @param content 代码内容
* @return 格式化后的代码
*/
public static String formatJavaCode(String content) {
// 使用正则表达式替换多个连续的空行为两个空行(保留适当的间距)
// 但要保留类声明前、方法前等重要位置的空行
StringBuilder result = new StringBuilder();
String[] lines = content.split("\\n");
boolean lastLineEmpty = false;
boolean inClassDeclaration = false;
for (String line : lines) {
boolean currentLineEmpty = line.trim().isEmpty();
// 检查是否进入类声明
if (line.contains(" class ") || line.contains(" interface ") || line.contains(" enum ")) {
inClassDeclaration = true;
}
// 保留类声明前的空行
if (inClassDeclaration && line.contains("{") && lastLineEmpty) {
result.append("\n"); // 保留类声明前的空行
}
// 对于普通代码,最多保留一个空行
if (currentLineEmpty && lastLineEmpty) {
continue;
}
// 特殊处理:方法之间保留一个空行
if (line.startsWith(" public") || line.startsWith(" private") ||
line.startsWith(" protected") || line.startsWith(" @")) {
if (result.length() > 0 && !lastLineEmpty) {
result.append("\n");
}
}
result.append(line).append("\n");
lastLineEmpty = currentLineEmpty;
}
return result.toString();
} }
} }

View File

@@ -1,8 +1,15 @@
package ${package.Mapper}; package ${package.Mapper};
<#list importMapperFrameworkPackages as pkg> <#list importMapperFrameworkPackages as pkg>
<#if pkg?contains(".")>
import ${pkg}; import ${pkg};
<#else>
import ${superMapperClass};
</#if>
</#list> </#list>
<#if package.Entity??>
import ${package.Entity}.${entity};
</#if>
<#if importMapperJavaPackages?size !=0> <#if importMapperJavaPackages?size !=0>
<#list importMapperJavaPackages as pkg> <#list importMapperJavaPackages as pkg>
@@ -22,9 +29,9 @@ import ${pkg};
@${mapperAnnotationClass.simpleName} @${mapperAnnotationClass.simpleName}
</#if> </#if>
<#if kotlin> <#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}> { interface ${table.mapperName} : ${superMapperClass?substring(superMapperClass?last_index_of(".") + 1)}<${entity}> {
<#else> <#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { public interface ${table.mapperName} extends ${superMapperClass?substring(superMapperClass?last_index_of(".") + 1)}<${entity}> {
</#if> </#if>
<#list mapperMethodList as m> <#list mapperMethodList as m>

View File

@@ -1,7 +1,7 @@
package ${package.Service}; package ${package.Service};
import ${package.Entity}.${entity}; import ${package.Entity}.${entity};
import ${superServiceClassPackage}; import ${superServiceClass};
/** /**
* <p> * <p>
@@ -12,9 +12,9 @@ import ${superServiceClassPackage};
* @since ${date} * @since ${date}
*/ */
<#if kotlin> <#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}> interface ${table.serviceName} : ${superServiceClass?substring(superServiceClass?last_index_of(".") + 1)}<${entity}>
<#else> <#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { public interface ${table.serviceName} extends ${superServiceClass?substring(superServiceClass?last_index_of(".") + 1)}<${entity}> {
} }
</#if> </#if>

View File

@@ -5,7 +5,7 @@ import ${package.Mapper}.${table.mapperName};
<#if generateService> <#if generateService>
import ${package.Service}.${table.serviceName}; import ${package.Service}.${table.serviceName};
</#if> </#if>
import ${superServiceImplClassPackage}; import ${superServiceImplClass};
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**