Skip to content

Commit 60b73b8

Browse files
author
wanghaiming
committed
whm 支持自动生成的Java代码合并,对于基于freemarker生成的代码目前不支持
1 parent 00258af commit 60b73b8

11 files changed

Lines changed: 259 additions & 111 deletions

File tree

java-generator-core/pom.xml

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,17 +105,24 @@
105105
<dependency>
106106
<groupId>com.github.javaparser</groupId>
107107
<artifactId>javaparser-core</artifactId>
108+
<version>3.2.10</version>
109+
<exclusions>
110+
<exclusion>
111+
<groupId>org.mybatis.generator.maven</groupId>
112+
<artifactId>java-generator-maven-plugin</artifactId>
113+
</exclusion>
114+
</exclusions>
108115
</dependency>
109116
<!--<dependency>-->
110117
<!--<groupId>com.microsoft.sqlserver</groupId>-->
111118
<!--<artifactId>sqljdbc4</artifactId>-->
112119
<!--<version>6.0</version>-->
113120
<!--</dependency>-->
114-
<!--<dependency>-->
115-
<!--<groupId>org.apache.ibatis</groupId>-->
116-
<!--<artifactId>ibatis-core</artifactId>-->
117-
<!--<version>3.0</version>-->
118-
<!--</dependency>-->
121+
<dependency>
122+
<groupId>org.apache.ibatis</groupId>
123+
<artifactId>ibatis-core</artifactId>
124+
<version>3.0</version>
125+
</dependency>
119126
<dependency>
120127
<groupId>org.freemarker</groupId>
121128
<artifactId>freemarker</artifactId>
@@ -129,6 +136,12 @@
129136
<groupId>org.springframework</groupId>
130137
<artifactId>spring-tx</artifactId>
131138
</dependency>
139+
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
140+
<dependency>
141+
<groupId>com.google.guava</groupId>
142+
<artifactId>guava</artifactId>
143+
<version>23.0-rc1</version>
144+
</dependency>
132145

133146
</dependencies>
134147

java-generator-core/src/main/java/org/mybatis/generator/api/MyBatisGenerator.java

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
package org.mybatis.generator.api;
1717

18+
import static org.mybatis.generator.internal.JavaFileMergerJaxp.mergeJavaFile;
1819
import static org.mybatis.generator.internal.util.ClassloaderUtility.getCustomClassloader;
1920
import static org.mybatis.generator.internal.util.JavaBeansUtil.getCamelCaseString;
2021
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
@@ -222,16 +223,6 @@ public void generate(ProgressCallback callback, Set<String> contextIds,
222223
if (callback == null) {
223224
callback = new NullProgressCallback();
224225
}
225-
/**
226-
* 如果JavaServiceGeneratorConfiguration存在则调用相关方法
227-
*/
228-
for (Context c:configuration.getContexts()) {
229-
if (c.getJavaServiceGeneratorConfiguration() != null)
230-
JavaServiceGenerator.addJavaServiceGenerator(assignmentServiceTemplateEntity());
231-
232-
if (c.getJavaDomainGeneratorConfiguration() != null)
233-
JavaDomainGenerator.addJavaDomainGenerator(assignmentDomainTemplateEntity());
234-
}
235226

236227
generatedJavaFiles.clear();
237228
generatedXmlFiles.clear();
@@ -280,6 +271,20 @@ public void generate(ProgressCallback callback, Set<String> contextIds,
280271
context.generateFiles(callback, generatedJavaFiles,
281272
generatedXmlFiles, warnings);
282273
}
274+
/**
275+
* 如果JavaServiceGeneratorConfiguration存在则调用相关方法
276+
*/
277+
278+
for (Context c:configuration.getContexts()) {
279+
if (c.getJavaServiceGeneratorConfiguration() != null) {
280+
281+
JavaServiceGenerator.addJavaServiceGenerator(assignmentServiceTemplateEntity());
282+
}
283+
284+
if (c.getJavaDomainGeneratorConfiguration() != null) {
285+
JavaDomainGenerator.addJavaDomainGenerator(assignmentDomainTemplateEntity());
286+
}
287+
}
283288

284289
// now save the files
285290
if (writeFiles) {
@@ -315,15 +320,18 @@ private void writeGeneratedJavaFile(GeneratedJavaFile gjf, ProgressCallback call
315320
targetFile = new File(directory, gjf.getFileName());
316321
if (targetFile.exists()) {
317322
if (shellCallback.isMergeSupported()) {
318-
319323
source = shellCallback.mergeJavaFile(gjf
320324
.getFormattedContent(), targetFile
321325
.getAbsolutePath(),
322326
MergeConstants.OLD_ELEMENT_TAGS,
323327
gjf.getFileEncoding());
324328

325329
} else if (shellCallback.isOverwriteEnabled()) {
326-
source = gjf.getFormattedContent();
330+
source = mergeJavaFile(gjf
331+
.getFormattedContent(), targetFile
332+
.getAbsolutePath(),
333+
gjf.getFileEncoding());
334+
// source = gjf.getFormattedContent();
327335
warnings.add(getString("Warning.11", //$NON-NLS-1$
328336
targetFile.getAbsolutePath()));
329337
} else {
@@ -469,10 +477,18 @@ public List<GeneratedXmlFile> getGeneratedXmlFiles() {
469477
public List<ServiceTemplateEntity> assignmentServiceTemplateEntity(){
470478
List<Context> contexts = configuration.getContexts();
471479
List<ServiceTemplateEntity> serviceTemplateEntities = new ArrayList<>();
480+
boolean flag;
472481
for (Context c:contexts){
473482
JavaServiceGeneratorConfiguration jgc = c.getJavaServiceGeneratorConfiguration();
474483
List<TableConfiguration> tableConfigurations = c.getTableConfigurations();
475484
for (TableConfiguration t:tableConfigurations){
485+
flag = false;
486+
for (GeneratedJavaFile gjf : generatedJavaFiles) {
487+
if (gjf.getFileName().contains("WithBLOBs")&& gjf.getFileName().contains(t.getDomainObjectName())) {
488+
flag = true;
489+
break;
490+
}
491+
}
476492
String domainObjectName = this.getDomainObjectName(t);
477493
ServiceTemplateEntity serviceTemplateEntity = new ServiceTemplateEntity();
478494
serviceTemplateEntity.setClassName(domainObjectName+"Service");
@@ -484,6 +500,7 @@ public List<ServiceTemplateEntity> assignmentServiceTemplateEntity(){
484500
serviceTemplateEntity.setModelClazz(domainObjectName);
485501
serviceTemplateEntity.setMapperPackage(c.getJavaClientGeneratorConfiguration().getTargetPackage()+"."+domainObjectName+"Mapper");
486502
serviceTemplateEntity.setModelPackage(c.getJavaModelGeneratorConfiguration().getTargetPackage()+"."+domainObjectName);
503+
serviceTemplateEntity.setColumnsHasBLOB(flag);
487504
serviceTemplateEntities.add(serviceTemplateEntity);
488505
}
489506
}

java-generator-core/src/main/java/org/mybatis/generator/codegen/freemarker/TemplateEntity/ServiceTemplateEntity.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ public class ServiceTemplateEntity {
1717
private String projectTargetPackage;//Service生成的目标工程包
1818
private String generatedDate = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//代码生成日期
1919
private String generatedTime = new SimpleDateFormat("HH:mm").format(new Date());//代码生成时间
20+
private boolean columnsHasBLOB;//是否包含BLOB字段
2021

2122
public String getTemplatePackage() {
2223
return templatePackage;
@@ -89,4 +90,12 @@ public String getGeneratedDate() {
8990
public String getGeneratedTime() {
9091
return generatedTime;
9192
}
93+
94+
public boolean isColumnsHasBLOB() {
95+
return columnsHasBLOB;
96+
}
97+
98+
public void setColumnsHasBLOB(boolean columnsHasBLOB) {
99+
this.columnsHasBLOB = columnsHasBLOB;
100+
}
92101
}

java-generator-core/src/main/java/org/mybatis/generator/config/Context.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,7 @@ public void introspectTables(ProgressCallback callback,
700700

701701
callback.checkCancel();
702702
}
703+
703704
} finally {
704705
closeConnection(connection);
705706
}
@@ -752,7 +753,6 @@ public void generateFiles(ProgressCallback callback,
752753
pluginConfiguration.getConfigurationType(), id));
753754
}
754755
}
755-
756756
if (introspectedTables != null) {
757757
for (IntrospectedTable introspectedTable : introspectedTables) {
758758
callback.checkCancel();
@@ -839,4 +839,20 @@ public ConnectionFactoryConfiguration getConnectionFactoryConfiguration() {
839839
public void setConnectionFactoryConfiguration(ConnectionFactoryConfiguration connectionFactoryConfiguration) {
840840
this.connectionFactoryConfiguration = connectionFactoryConfiguration;
841841
}
842+
843+
// /**
844+
// * 判断表内是否含有BLOB字段的方法
845+
// * @param tableConfiguration
846+
// * @return
847+
// */
848+
// public boolean hasBLOBColumns(TableConfiguration tableConfiguration){
849+
// boolean columnsHasBLOB = false;
850+
// System.out.println(introspectedTables);
851+
// for (IntrospectedTable i:introspectedTables){
852+
// if (i.getTableConfiguration().getTableName().equals(tableConfiguration.getTableName())){
853+
// columnsHasBLOB = i.hasBLOBColumns() ? true :false;
854+
// }
855+
// }
856+
// return columnsHasBLOB;
857+
// }
842858
}
Lines changed: 93 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,115 @@
11
package org.mybatis.generator.internal;
22

3-
import org.mybatis.generator.api.GeneratedJavaFile;
4-
import org.mybatis.generator.api.GeneratedXmlFile;
5-
import org.mybatis.generator.exception.ShellException;
6-
import org.w3c.dom.Document;
7-
import org.w3c.dom.DocumentType;
8-
import org.xml.sax.InputSource;
9-
103

11-
import javax.xml.parsers.DocumentBuilder;
12-
import javax.xml.parsers.DocumentBuilderFactory;
13-
import java.io.*;
4+
import com.github.javaparser.JavaParser;
5+
import com.github.javaparser.ast.CompilationUnit;
6+
import com.github.javaparser.ast.ImportDeclaration;
7+
import com.github.javaparser.ast.Node;
8+
import com.github.javaparser.ast.NodeList;
9+
import com.github.javaparser.ast.body.FieldDeclaration;
10+
import com.github.javaparser.ast.body.MethodDeclaration;
11+
import com.github.javaparser.ast.body.TypeDeclaration;
12+
import org.mybatis.generator.config.MergeConstants;
13+
import org.mybatis.generator.exception.ShellException;
1414

15-
import static org.springframework.util.FileCopyUtils.copy;
15+
import java.io.File;
16+
import java.io.FileNotFoundException;
17+
import java.util.ArrayList;
18+
import java.util.HashSet;
19+
import java.util.List;
20+
import java.util.Set;
1621

1722

1823
/**
1924
* Created by whm on 2017/7/24.
2025
*/
2126
public class JavaFileMergerJaxp {
2227
public static String mergeJavaFile(String newFileSource,
23-
String existingFileFullPath, String[] javadocTags, String fileEncoding)
24-
throws ShellException {
25-
// System.out.println(existingFileFullPath);
26-
27-
StringWriter out = new StringWriter();
28-
try {
29-
Reader in = new FileReader(existingFileFullPath);
30-
copy(in,out);
31-
String regerx = "\\/\\*\\*[\\s\\S]*(@mbg.generated)[\\s\\S]*\\}";
32-
// String str = out.toString().replaceAll(regerx,"");
33-
// System.out.println(str);
34-
} catch (IOException e) {
35-
e.printStackTrace();
36-
}
28+
String existingFileFullPath, String fileEncoding)
29+
throws ShellException, FileNotFoundException {
30+
return getNewJavaFile(newFileSource,existingFileFullPath);
31+
// List<String> commentedNodeList = getCommentedNodeList(existingFileFullPath);
32+
// if (commentedNodeList.size()>0) {
33+
// StringBuffer sb = new StringBuffer(newFileSource.substring(0, newFileSource.lastIndexOf("}")));
34+
// for (String str : commentedNodeList) {
35+
// sb.append(" "+str+System.getProperty("line.separator"));
36+
// }
37+
// return sb.append(System.getProperty("line.separator")+"}").toString();
38+
// }else {
39+
// return newFileSource;
40+
// }
3741

38-
39-
return null;
4042
}
43+
public static String getNewJavaFile(String newFileSource, String existingFileFullPath) throws FileNotFoundException {
44+
45+
CompilationUnit newCompilationUnit = JavaParser.parse(newFileSource);
46+
StringBuffer sb = new StringBuffer(newCompilationUnit.getPackageDeclaration().get().toString());
47+
newCompilationUnit.removePackageDeclaration();
48+
49+
//合并imports
50+
CompilationUnit existingCompilationUnit = JavaParser.parse(new File(existingFileFullPath));
51+
NodeList<ImportDeclaration> imports = newCompilationUnit.getImports();
52+
imports.addAll(existingCompilationUnit.getImports());
53+
Set importSet = new HashSet<ImportDeclaration>();
54+
importSet.addAll(imports);
4155

56+
// importSet.forEach(System.out::println);
57+
NodeList<ImportDeclaration> newImports = new NodeList<>();
58+
newImports.addAll(importSet);
59+
newCompilationUnit.setImports(newImports);
60+
for (ImportDeclaration i:newCompilationUnit.getImports()) {
61+
sb.append(i.toString());
62+
}
63+
64+
NodeList<TypeDeclaration<?>> types = newCompilationUnit.getTypes();
65+
NodeList<TypeDeclaration<?>> oldTypes = existingCompilationUnit.getTypes();
4266

67+
for (int i = 0;i<types.size();i++) {
68+
//截取Class
69+
String classNameInfo = types.get(i).toString().substring(0, types.get(i).toString().indexOf("{")+1);
70+
sb.append(classNameInfo);
71+
//合并fields
72+
List<FieldDeclaration> fields = types.get(i).getFields();
73+
List<FieldDeclaration> oldFields = oldTypes.get(i).getFields();
74+
List<FieldDeclaration> newFields = new ArrayList<>();
75+
HashSet<FieldDeclaration> fieldDeclarations = new HashSet<>();
76+
fieldDeclarations.addAll(fields);
77+
fieldDeclarations.addAll(oldFields);
78+
newFields.addAll(fieldDeclarations);
79+
for (FieldDeclaration f: newFields){
80+
sb.append(f.toString());
81+
}
4382

4483

45-
public static void getMergedSource(GeneratedJavaFile generatedXmlFile,
46-
File existingFile) throws ShellException {
47-
BufferedReader bs = null;
48-
try {
49-
bs = new BufferedReader(new FileReader(existingFile));
50-
String line = null;
51-
String regEx = "";
52-
while((line = bs.readLine()) != null){
53-
// System.out.println(line);
84+
//合并methods
85+
List<MethodDeclaration> methods = types.get(i).getMethods();
86+
List<MethodDeclaration> existingMethods = oldTypes.get(i).getMethods();
87+
for (MethodDeclaration f: methods){
88+
sb.append(f.toString());
89+
}
90+
for (MethodDeclaration m:existingMethods){
91+
boolean flag = true;
92+
for (String tag : MergeConstants.OLD_ELEMENT_TAGS) {
93+
if (m.toString().contains(tag)) {
94+
flag = false;
95+
break;
96+
}
97+
}
98+
if (flag){
99+
sb.append(m.toString());
100+
}
101+
}
102+
103+
//判断是否有内部类
104+
types.get(i).getChildNodes();
105+
for (Node n:types.get(i).getChildNodes()){
106+
if (n.toString().contains("class")){
107+
sb.append(n.toString());
108+
}
54109
}
55110

56-
}catch (Exception e){
57-
e.printStackTrace();
58111
}
112+
113+
return sb.append("}").toString();
59114
}
60115
}

0 commit comments

Comments
 (0)