Skip to content

Commit 9fa1004

Browse files
committed
code cleanup and refactor
1 parent 79ef7f5 commit 9fa1004

23 files changed

+154
-78
lines changed

src/main/java/io/github/ngbsn/generator/AssociationMappingsGenerator.java

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,13 @@
1717
*/
1818
public class AssociationMappingsGenerator {
1919

20+
21+
private AssociationMappingsGenerator() {
22+
}
23+
24+
/**
25+
* Generate both UniDirectional and BiDirectional association mappings for all tables
26+
*/
2027
public static void generateMappings() {
2128
Iterator<Map.Entry<String, Table>> it = tablesMap.entrySet().iterator();
2229
while (it.hasNext()) {
@@ -44,9 +51,7 @@ public static void generateMappings() {
4451
//Case1: There are some fields that are not foreign keys. So separate entity is needed to track Link Table
4552
//Case2: All fields are foreign keys. But, the relation exits between 2 or more entities
4653
//Add @ManyToOne for each foreignKey and corresponding @OneToMany in referenced Table
47-
foreignKeyConstraintList.forEach(foreignKeyConstraint -> {
48-
addBothSideUniDirectionalMappings(table, foreignKeyConstraint);
49-
});
54+
foreignKeyConstraintList.forEach(foreignKeyConstraint -> addBothSideUniDirectionalMappings(table, foreignKeyConstraint));
5055
}
5156
}
5257
}

src/main/java/io/github/ngbsn/generator/BiDirectionalMappingsGenerator.java

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
import io.github.ngbsn.model.Column;
44
import io.github.ngbsn.model.ForeignKeyConstraint;
55
import io.github.ngbsn.model.Table;
6-
import io.github.ngbsn.model.annotations.fieldAnnotations.JoinColumnAnnotation;
7-
import io.github.ngbsn.model.annotations.fieldAnnotations.JoinTableAnnotation;
8-
import io.github.ngbsn.model.annotations.fieldAnnotations.ManyToManyAnnotation;
6+
import io.github.ngbsn.model.annotations.field.JoinColumnAnnotation;
7+
import io.github.ngbsn.model.annotations.field.JoinTableAnnotation;
8+
import io.github.ngbsn.model.annotations.field.ManyToManyAnnotation;
99
import io.github.ngbsn.util.Util;
1010

1111
import java.util.HashSet;
@@ -15,6 +15,15 @@
1515
import static io.github.ngbsn.generator.ModelGenerator.tablesMap;
1616

1717
public class BiDirectionalMappingsGenerator {
18+
19+
private BiDirectionalMappingsGenerator() {
20+
}
21+
22+
/**
23+
* Generate BiDirectional Mappings (many-to-many) for a specific table
24+
* @param table The table to be processed
25+
* @param foreignKeyConstraintList List of generated foreignKeyConstraintList models
26+
*/
1827
static void addBiDirectionalMappings(Table table, List<ForeignKeyConstraint> foreignKeyConstraintList) {
1928
Table table1 = tablesMap.get(foreignKeyConstraintList.get(0).getReferencedTableName().replaceAll("[\"']", ""));
2029
Table table2 = tablesMap.get(foreignKeyConstraintList.get(1).getReferencedTableName().replaceAll("[\"']", ""));

src/main/java/io/github/ngbsn/generator/JPACodeGenerator.java

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import freemarker.template.TemplateException;
77
import freemarker.template.TemplateExceptionHandler;
88
import io.github.ngbsn.model.Table;
9+
import lombok.extern.slf4j.Slf4j;
910
import org.slf4j.Logger;
1011
import org.slf4j.LoggerFactory;
1112

@@ -18,27 +19,50 @@
1819

1920
import static io.github.ngbsn.util.Util.packageNameToFolderStructure;
2021

22+
@Slf4j
2123
public class JPACodeGenerator {
2224
private static final Logger logger = LoggerFactory.getLogger(JPACodeGenerator.class);
2325

24-
public static void main(String[] args) throws TemplateException, IOException {
25-
String sqlScript = new BufferedReader(
26-
new InputStreamReader(new FileInputStream(args[0]), StandardCharsets.UTF_8))
27-
.lines()
28-
.collect(Collectors.joining("\n"));
29-
generateCode(sqlScript, args[1]);
26+
public static void main(final String[] args) throws TemplateException, IOException {
27+
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), StandardCharsets.UTF_8))) {
28+
String sqlScript = bufferedReader
29+
.lines()
30+
.collect(Collectors.joining("\n"));
31+
generateCode(sqlScript, args[1]);
32+
} catch (Exception e) {
33+
log.error("Error occurred while running the tool", e);
34+
}
3035
}
3136

37+
/**
38+
*
39+
* @param sqlScript The input DDL commands used for generating the models
40+
* @param packageName package name for the entities sources to be generated
41+
* @throws IOException Thrown if template couldn't be read
42+
* @throws TemplateException Thrown if template couldn't be processed
43+
*/
3244
public static void generateCode(final String sqlScript, final String packageName) throws IOException, TemplateException {
3345
logger.info("sql script {}", sqlScript);
3446
List<Table> tables = generateModels(sqlScript);
3547
processTemplate(tables, packageName);
3648
}
3749

50+
/**
51+
* Generate the models needed to generate the sources
52+
* @param sqlScript The input DDL commands used for generating the models
53+
* @return List of Table models
54+
*/
3855
private static List<Table> generateModels(final String sqlScript) {
3956
return ModelGenerator.parse(sqlScript);
4057
}
4158

59+
/**
60+
* This method processes the Apache FreeMarker entity template using the generated models
61+
* @param tables Generated models
62+
* @param packageName package name for the entities sources to be generated
63+
* @throws IOException Thrown if template couldn't be read
64+
* @throws TemplateException Thrown if template cannot be processed
65+
*/
4266
private static void processTemplate(final List<Table> tables, final String packageName) throws IOException, TemplateException {
4367
/* Create and adjust the configuration singleton */
4468
Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);

src/main/java/io/github/ngbsn/generator/ModelGenerator.java

Lines changed: 43 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44
import io.github.ngbsn.model.EmbeddableClass;
55
import io.github.ngbsn.model.ForeignKeyConstraint;
66
import io.github.ngbsn.model.Table;
7-
import io.github.ngbsn.model.annotations.entityAnnotations.EntityAnnotation;
8-
import io.github.ngbsn.model.annotations.entityAnnotations.TableAnnotation;
9-
import io.github.ngbsn.model.annotations.fieldAnnotations.ColumnAnnotation;
10-
import io.github.ngbsn.model.annotations.fieldAnnotations.NotNullAnnotation;
7+
import io.github.ngbsn.model.annotations.entity.EntityAnnotation;
8+
import io.github.ngbsn.model.annotations.entity.TableAnnotation;
9+
import io.github.ngbsn.model.annotations.field.ColumnAnnotation;
10+
import io.github.ngbsn.model.annotations.field.NotNullAnnotation;
1111
import io.github.ngbsn.util.SQLToJavaMapping;
1212
import io.github.ngbsn.util.Util;
1313
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
@@ -27,9 +27,20 @@
2727
* It will also extract all the columns from the script and add to the Table model
2828
*/
2929
public class ModelGenerator {
30+
31+
public static final String REGEX_ALL_QUOTES = "[\"']";
32+
33+
private ModelGenerator() {
34+
}
35+
3036
private static final Logger logger = LoggerFactory.getLogger(ModelGenerator.class);
3137
protected static Map<String, Table> tablesMap = new HashMap<>();
3238

39+
/**
40+
* Parse the DDL statements using JSQL parser
41+
* @param sqlScript The input DDL commands used for generating the models
42+
* @return List of Tables models
43+
*/
3344
public static List<Table> parse(final String sqlScript) {
3445
try {
3546
Statements statements = CCJSqlParserUtil.parseStatements(sqlScript);
@@ -40,7 +51,7 @@ public static List<Table> parse(final String sqlScript) {
4051
} catch (Exception e) {
4152
logger.error("Error occurred", e);
4253
}
43-
return null;
54+
return new ArrayList<>();
4455
}
4556

4657
/**
@@ -51,16 +62,15 @@ public static void clearTablesMap() {
5162
}
5263

5364
/**
54-
* Iterate over all the Create Table statements and prepare the list of Table Model
55-
*
56-
* @param statements set of statements
65+
* Iterate over all the JSQL Create Table statements and prepare the list of Table Model
66+
* @param statements Set of JSQL statements
5767
*/
58-
private static void processCreateTableStatements(Statements statements) {
68+
private static void processCreateTableStatements(final Statements statements) {
5969
statements.getStatements().forEach(statement -> {
6070
//Iterating over all Tables
6171
if (statement instanceof CreateTable parsedTable) {
6272
Table table = new Table();
63-
table.setTableName(parsedTable.getTable().getName().replaceAll("[\"']", ""));
73+
table.setTableName(parsedTable.getTable().getName().replaceAll(REGEX_ALL_QUOTES, ""));
6474
tablesMap.put(table.getTableName(), table);
6575
table.setClassName(Util.convertSnakeCaseToCamelCase(table.getTableName(), true));
6676

@@ -82,26 +92,25 @@ private static void processCreateTableStatements(Statements statements) {
8292
extractPrimaryKeys(optionalIndex.orElse(null), table);
8393

8494
//extract foreign keys
85-
List<Index> foreignKeyIndexes = parsedTable.getIndexes().stream().filter(index -> index instanceof ForeignKeyIndex).toList();
95+
List<Index> foreignKeyIndexes = parsedTable.getIndexes().stream().filter(ForeignKeyIndex.class::isInstance).toList();
8696
extractForeignKeys(foreignKeyIndexes, table);
8797
}
8898
});
8999
}
90100

91101
/**
92-
* Iterate over all the Alter Table statements and prepare the list of Table Model
93-
*
94-
* @param statements set of statements
102+
* Iterate over all the JSQL Alter Table statements and prepare the list of Table Model
103+
* @param statements Set of JSQL statements
95104
*/
96-
private static void processAlterTableStatements(Statements statements) {
105+
private static void processAlterTableStatements(final Statements statements) {
97106
statements.getStatements().forEach(statement -> {
98107
//Iterating over all Tables
99108
// Look for primary and foreign keys in ALTER TABLE constraints
100109
if (statement instanceof Alter alterTable) {
101-
Table table = tablesMap.get(alterTable.getTable().getName().replaceAll("[\"']", ""));
110+
Table table = tablesMap.get(alterTable.getTable().getName().replaceAll(REGEX_ALL_QUOTES, ""));
102111
List<Index> foreignKeyIndexes = new ArrayList<>();
103112
alterTable.getAlterExpressions().forEach(alterExpression -> {
104-
if (alterExpression.getIndex() instanceof ForeignKeyIndex foreignKeyIndex) {
113+
if (alterExpression.getIndex() instanceof ForeignKeyIndex) {
105114
//case: ALTER TABLE FOREIGN KEY
106115
foreignKeyIndexes.add(alterExpression.getIndex());
107116
} else if (alterExpression.getIndex().getType().equals("PRIMARY KEY")) {
@@ -116,39 +125,39 @@ private static void processAlterTableStatements(Statements statements) {
116125

117126

118127
/**
119-
* Looking for all foreign keys in this table and adding it to our model
120-
*
121-
* @param foreignKeyIndexes List of foreign key indexes
128+
* Looking for all JSQL foreign keys in this table and adding it to our model
129+
* @param foreignKeyIndexes List of JSQL foreign key indexes
122130
* @param table Table model
123131
*/
124-
private static void extractForeignKeys(List<Index> foreignKeyIndexes, Table table) {
132+
private static void extractForeignKeys(final List<Index> foreignKeyIndexes, final Table table) {
125133
if (!foreignKeyIndexes.isEmpty()) {
126134
foreignKeyIndexes.forEach(index -> {
127135
if (index instanceof ForeignKeyIndex foreignKeyIndex) {
128136
ForeignKeyConstraint foreignKeyConstraint = new ForeignKeyConstraint();
129137
foreignKeyConstraint.setColumns(foreignKeyIndex.getColumnsNames()
130-
.stream().map(s -> s.replaceAll("[\"']", "")).collect(Collectors.toList()));
138+
.stream().map(s -> s.replaceAll(REGEX_ALL_QUOTES, "")).toList());
131139
foreignKeyConstraint.setReferencedColumns(foreignKeyIndex.getReferencedColumnNames()
132-
.stream().map(s -> s.replaceAll("[\"']", "")).collect(Collectors.toList()));
140+
.stream().map(s -> s.replaceAll(REGEX_ALL_QUOTES, "")).toList());
133141
foreignKeyConstraint.setReferencedTableName(foreignKeyIndex.getTable().getName()
134-
.replaceAll("[\"']", ""));
142+
.replaceAll(REGEX_ALL_QUOTES, ""));
135143
table.getForeignKeyConstraints().add(foreignKeyConstraint);
144+
136145
}
137146
});
138147
}
139148
}
140149

141150
/**
142-
* Extracting primary key information from the parsed data and setting them into the Table model
151+
* Extracting primary key information from the JSQL parsed data and setting them into the Table model
143152
*
144-
* @param primaryKeyIndex primaryKeyIndex
153+
* @param primaryKeyIndex JSQL primaryKeyIndex
145154
* @param table Table model
146155
*/
147-
private static void extractPrimaryKeys(Index primaryKeyIndex, Table table) {
156+
private static void extractPrimaryKeys(final Index primaryKeyIndex, final Table table) {
148157
List<Index.ColumnParams> columnParamsList = primaryKeyIndex != null ? primaryKeyIndex.getColumns() : null;
149158
if (columnParamsList != null) {
150159
Set<Column> primaryKeyColumns = table.getColumns().stream().
151-
filter(column -> columnParamsList.stream().anyMatch(columnParams -> columnParams.getColumnName().replaceAll("[\"']", "").equals(column.getColumnName()))).collect(Collectors.toSet());
160+
filter(column -> columnParamsList.stream().anyMatch(columnParams -> columnParams.getColumnName().replaceAll(REGEX_ALL_QUOTES, "").equals(column.getColumnName()))).collect(Collectors.toSet());
152161

153162
if (columnParamsList.size() > 1) {
154163
table.setNumOfPrimaryKeyColumns(columnParamsList.size());
@@ -170,22 +179,21 @@ private static void extractPrimaryKeys(Index primaryKeyIndex, Table table) {
170179
}
171180

172181
/**
173-
* Generate column models for all the parsed table
174-
*
175-
* @param parsedTable Parsed table
176-
* @param columns List of generated column models
182+
* Generate column models for the JSQL parsed table
183+
* @param parsedTable JSQL CreateTable
184+
* @param columns Set of generated column models
177185
*/
178-
private static void extractColumns(CreateTable parsedTable, Set<Column> columns) {
186+
private static void extractColumns(final CreateTable parsedTable, final Set<Column> columns) {
179187
parsedTable.getColumnDefinitions().forEach(columnDefinition -> {
180188
Column column = new Column();
181189
columns.add(column);
182190
Set<String> columnAnnotations = new HashSet<>();
183191
column.setAnnotations(columnAnnotations);
184-
column.setColumnName(columnDefinition.getColumnName().replaceAll("[\"']", ""));
192+
column.setColumnName(columnDefinition.getColumnName().replaceAll(REGEX_ALL_QUOTES, ""));
185193
//Adding @Column
186194
columnAnnotations.add(ColumnAnnotation.builder().columnName(column.getColumnName()).build().toString());
187195
column.setFieldName(Util.convertSnakeCaseToCamelCase(column.getColumnName(), false));
188-
column.setType(SQLToJavaMapping.sqlToJavaMap.get(columnDefinition.getColDataType().getDataType()));
196+
column.setType(SQLToJavaMapping.getSqlToJavaMap().get(columnDefinition.getColDataType().getDataType()));
189197

190198
//Check for NOT NULL
191199
if (columnDefinition.getColumnSpecs() != null) {

src/main/java/io/github/ngbsn/generator/UniDirectionalMappingsGenerator.java

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import io.github.ngbsn.model.EmbeddableClass;
55
import io.github.ngbsn.model.ForeignKeyConstraint;
66
import io.github.ngbsn.model.Table;
7-
import io.github.ngbsn.model.annotations.fieldAnnotations.*;
7+
import io.github.ngbsn.model.annotations.field.*;
88
import io.github.ngbsn.util.Util;
99
import org.apache.commons.text.WordUtils;
1010

@@ -18,11 +18,13 @@
1818

1919
public class UniDirectionalMappingsGenerator {
2020

21+
private UniDirectionalMappingsGenerator() {
22+
}
23+
2124
/**
22-
* This method will handle each foreign key constraint in the table.
23-
*
24-
* @param table table
25-
* @param foreignKeyConstraint foreignKeyConstraint
25+
* Generate UniDirectional Mappings (one-to-many and many-to-one) for a specific table
26+
* @param table Table model
27+
* @param foreignKeyConstraint ForeignKeyConstraint model
2628
*/
2729
static void addBothSideUniDirectionalMappings(Table table, ForeignKeyConstraint foreignKeyConstraint) {
2830
Table referencedTable = tablesMap.get(foreignKeyConstraint.getReferencedTableName().replaceAll("[\"']", ""));
@@ -64,15 +66,15 @@ private static void handleSingleForeignKey(Table table, ForeignKeyConstraint for
6466
Column foreignKeyColumn = optionalColumn.get();
6567
//Check if foreign key is also a primary key, by iterating through the primary key list
6668
Optional<Column> optionalColumnPrimaryForeign = allPrimaryKeyColumns.stream().filter(column -> column.getColumnName() != null && column.getColumnName().equals(foreignKeyColumn.getColumnName())).findFirst();
67-
optionalColumnPrimaryForeign.ifPresentOrElse(column -> {
69+
optionalColumnPrimaryForeign.ifPresentOrElse(column ->
6870
//Case: Shared Primary key
6971
//If foreign key is a primary key, don't remove it from table.
7072
//Add a @MapsId annotation to the referenced table field
71-
parentTableField.getAnnotations().add(MapsIdAnnotation.builder().fieldName(column.getFieldName()).build().toString());
72-
}, () -> {
73+
parentTableField.getAnnotations().add(MapsIdAnnotation.builder().fieldName(column.getFieldName()).build().toString())
74+
, () ->
7375
//If foreign key is not a primary key, then remove it from the table
74-
optionalColumn.ifPresent(column -> table.getColumns().remove(column));
75-
});
76+
optionalColumn.ifPresent(column -> table.getColumns().remove(column))
77+
);
7678
}
7779
//Add a @JoinColumn annotation for the referenced table field
7880
parentTableField.getAnnotations().add(JoinColumnAnnotation.builder().name(foreignKeyConstraint.getReferencedColumns().get(0)).referencedColumnName(foreignKeyConstraint.getReferencedColumns().get(0)).build().toString());

src/main/java/io/github/ngbsn/maven/JPACodeGenMojo.java

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import io.github.ngbsn.generator.JPACodeGenerator;
44
import lombok.SneakyThrows;
5+
import lombok.extern.slf4j.Slf4j;
56
import org.apache.maven.plugin.AbstractMojo;
67
import org.apache.maven.plugin.MojoExecutionException;
78
import org.apache.maven.plugin.MojoFailureException;
@@ -17,6 +18,7 @@
1718
import java.util.stream.Collectors;
1819

1920
@Mojo(name = "parse-schema")
21+
@Slf4j
2022
public class JPACodeGenMojo extends AbstractMojo {
2123
private static final Logger logger = LoggerFactory.getLogger(JPACodeGenMojo.class);
2224

@@ -37,10 +39,16 @@ public class JPACodeGenMojo extends AbstractMojo {
3739
public void execute() throws MojoExecutionException, MojoFailureException {
3840
logger.info("Executing the goal parse-schema {} {}", sqlFilePath, packageName);
3941

40-
String sqlScript = new BufferedReader(
41-
new InputStreamReader(new FileInputStream(sqlFilePath), StandardCharsets.UTF_8))
42-
.lines()
43-
.collect(Collectors.joining("\n"));
44-
JPACodeGenerator.generateCode(sqlScript, packageName);
42+
try (BufferedReader bufferedReader = new BufferedReader(
43+
new InputStreamReader(new FileInputStream(sqlFilePath), StandardCharsets.UTF_8))) {
44+
String sqlScript = bufferedReader
45+
.lines()
46+
.collect(Collectors.joining("\n"));
47+
JPACodeGenerator.generateCode(sqlScript, packageName);
48+
} catch (Exception e) {
49+
log.error("Error occurred while running the plugin", e);
50+
}
51+
52+
4553
}
4654
}

src/main/java/io/github/ngbsn/model/annotations/entityAnnotations/EntityAnnotation.java renamed to src/main/java/io/github/ngbsn/model/annotations/entity/EntityAnnotation.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package io.github.ngbsn.model.annotations.entityAnnotations;
1+
package io.github.ngbsn.model.annotations.entity;
22

33
import io.github.ngbsn.model.annotations.Annotation;
44

src/main/java/io/github/ngbsn/model/annotations/entityAnnotations/TableAnnotation.java renamed to src/main/java/io/github/ngbsn/model/annotations/entity/TableAnnotation.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package io.github.ngbsn.model.annotations.entityAnnotations;
1+
package io.github.ngbsn.model.annotations.entity;
22

33
import io.github.ngbsn.model.annotations.Annotation;
44
import lombok.Builder;

0 commit comments

Comments
 (0)