Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ apply plugin: 'java'
buildscript {
dependencies {
classpath 'com.h2database:h2:1.4.197'
classpath 'com.smartnews:jpa-entity-generator:0.99.8'
classpath 'com.smartnews:jpa-entity-generator:0.99.9'
}
}

Expand Down Expand Up @@ -46,7 +46,7 @@ Maven plugin to run the code generator is also available.
<plugin>
<groupId>com.smartnews</groupId>
<artifactId>maven-jpa-entity-generator-plugin</artifactId>
<version>0.99.8</version>
<version>0.99.9</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
Expand Down
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ dependencies {
// Can be removed after no javax support
testCompile 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final'
testCompile 'jakarta.persistence:jakarta.persistence-api:3.0.0'
testCompile 'org.springframework.data:spring-data-jpa:2.3.2.RELEASE'

testCompileOnly 'org.projectlombok:lombok:1.18.2'
// Can be removed after no javax support
Expand Down
54 changes: 39 additions & 15 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,24 +66,24 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
<!-- Please refer to this page https://central.sonatype.org/publish/publish-maven/#gpg-signed-components -->
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-gpg-plugin</artifactId>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <id>sign-artifacts</id>-->
<!-- <phase>verify</phase>-->
<!-- <goals>-->
<!-- <goal>sign</goal>-->
<!-- </goals>-->
<!--&lt;!&ndash; Please refer to this page https://central.sonatype.org/publish/publish-maven/#gpg-signed-components &ndash;&gt;-->
<!-- <configuration> -->
<!-- <keyname>${gpg.keyname}</keyname> -->
<!-- <passphraseServerId>${gpg.keyname}</passphraseServerId> -->
<!-- </configuration>-->
</execution>
</executions>
</plugin>
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
Expand Down Expand Up @@ -167,7 +167,7 @@
<dependency>
<groupId>com.smartnews</groupId>
<artifactId>jpa-entity-generator</artifactId>
<version>0.99.8</version>
<version>0.99.9</version>
<scope>compile</scope>
</dependency>
<dependency>
Expand All @@ -182,6 +182,30 @@
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>2.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.3.2.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>

</project>
34 changes: 34 additions & 0 deletions sample/src/main/resources/entityGenConfig-tpl.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
jdbcSettings:
url: "jdbc:mysql://10.228.131.93:3306/Activity"
username: "root"
password: "zqsc123$Mk"
driverClassName: "com.mysql.cj.jdbc.Driver"

useJsr310DateTime: true
generateJpaRepository: true
useShortClassNameAsEntityName: true
packageName: "com.eastmoney.market.welp.entity.master"
repositoryPackageName: "com.eastmoney.market.welp.repository.master"

classAnnotationRules:
- annotations:
- className: "org.hibernate.annotations.DynamicInsert"
- className: "org.hibernate.annotations.DynamicUpdate"
- className: "lombok.experimental.Accessors"
attributes:
- name: "chain"
value: "true"

# ---------------------------------------------------------
# *** Table scan mode ***

# Set the scan mode (possible values: All / RuleBased)
# - string value: 'All' (default) or 'RuleBased'
tableScanMode: 'RuleBased'

# If the "tableScanMode" is "RuleBased", the table scanner considers these rules
# - array of TableScanRule objects
# - tableName (string) / tableNames (array): string value that partially matches table names (case sensitive)
tableScanRules:
# - tableNames: ["tb_fkc_.*"]
- tableNames: [ "tb_welp_super_m1_config" ]
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

Expand Down Expand Up @@ -91,7 +93,11 @@ public static void generateAll(CodeGeneratorConfig originalConfig, boolean isJpa
Annotation entityAnnotation = Annotation.fromClassName(entityClassName);
AnnotationAttribute entityAnnotationValueAttr = new AnnotationAttribute();
entityAnnotationValueAttr.setName("name");
entityAnnotationValueAttr.setValue("\"" + data.getPackageName() + "." + data.getClassName() + "\"");
if (config.isUseShortClassNameAsEntityName()) {
entityAnnotationValueAttr.setValue("\"" + data.getClassName() + "\"");
} else {
entityAnnotationValueAttr.setValue("\"" + data.getPackageName() + "." + data.getClassName() + "\"");
}
entityAnnotation.getAttributes().add(entityAnnotationValueAttr);
entityClassAnnotationRule.setAnnotations(Arrays.asList(entityAnnotation));
entityClassAnnotationRule.setClassName(className);
Expand All @@ -103,6 +109,7 @@ public static void generateAll(CodeGeneratorConfig originalConfig, boolean isJpa
.filter(r -> r.matches(className))
.collect(toList()));

AtomicReference<String> primaryKeyType = new AtomicReference<>(null);
List<CodeRenderer.RenderingData.Field> fields = table.getColumns().stream().map(c -> {
CodeRenderer.RenderingData.Field f = new CodeRenderer.RenderingData.Field();

Expand All @@ -126,7 +133,7 @@ public static void generateAll(CodeGeneratorConfig originalConfig, boolean isJpa
f.setType(fieldTypeRule.get().getTypeName());
f.setPrimitive(isPrimitive(f.getType()));
} else {
f.setType(TypeConverter.toJavaType(c.getTypeCode()));
f.setType(TypeConverter.toJavaType(c.getTypeCode(), config.isUseJsr310DateTime()));
if (!c.isNullable() && config.isUsePrimitiveForNonNullField()) {
f.setType(TypeConverter.toPrimitiveTypeIfPossible(f.getType()));
}
Expand All @@ -145,6 +152,11 @@ public static void generateAll(CodeGeneratorConfig originalConfig, boolean isJpa

f.setAutoIncrement(c.isAutoIncrement());
f.setPrimaryKey(c.isPrimaryKey());

if (f.isPrimaryKey()) {
primaryKeyType.set(f.getType());
}

return f;

}).collect(toList());
Expand Down Expand Up @@ -219,6 +231,29 @@ public static void generateAll(CodeGeneratorConfig originalConfig, boolean isJpa
}
Files.write(path, code.getBytes());

// generate jpa repository if enabled
if (config.isGenerateJpaRepository() && primaryKeyType.get() != null) {
String repoInterfaceName = className + "Repository";

CodeRenderer.RenderingData repoData = new CodeRenderer.RenderingData();
repoData.setClassName(repoInterfaceName);
repoData.setPackageName(config.getRepositoryPackageName());
repoData.setImportRules(Arrays.asList(CodeGeneratorConfig.IMPORT_RULE_JPA_REPOSITORY,
ImportRule.createGlobal(data.getPackageName() + "." + className)));
repoData.setInterfaceNames(singletonList(String.format("JpaRepository<%s, %s>", className, primaryKeyType.get())));

String repoFilepath = config.getOutputDirectory()
+ "/" + repoData.getPackageName().replaceAll("\\.", "/")
+ "/" + repoInterfaceName + ".java";
Path repoPath = Paths.get(repoFilepath);
if (!Files.exists(repoPath)) {
Files.createFile(repoPath);
}

String repoCode = CodeRenderer.render("entityGen/repository.ftl", repoData);
Files.write(repoPath, repoCode.getBytes());
}

log.debug("path: {}, code: {}", path, code);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,5 @@ public static class Field {
private List<Annotation> annotations = new ArrayList<>();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ public class CodeGeneratorConfig implements Serializable {
ImportRule.createGlobal("lombok.AllArgsConstructor")
);

public static final ImportRule IMPORT_RULE_JPA_REPOSITORY
= ImportRule.createGlobal("org.springframework.data.jpa.repository.JpaRepository");

// ----------
// Preset

Expand Down Expand Up @@ -159,6 +162,16 @@ public void setUpPresetRules() {
// see also: https://github.com/rzwitserloot/lombok/issues/816
private boolean autoPreparationForLombokBuilderEnabled;

// Add support for the new java time API introduced by jsr310.
private boolean useJsr310DateTime;

// use short class name as the name attr of @Entity
private boolean useShortClassNameAsEntityName;

// generate jpa repository
private boolean generateJpaRepository;
private String repositoryPackageName;

private List<ImportRule> importRules = new ArrayList<>();

private List<ClassNameRule> classNameRules = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class TypeConverter {
private TypeConverter() {
}

public static String toJavaType(int typeCode) {
public static String toJavaType(int typeCode, boolean useJsr310DateTime) {
switch (typeCode) {
case Types.ARRAY:
return "Array";
Expand All @@ -30,6 +30,9 @@ public static String toJavaType(int typeCode) {
return "Clob";
// case Types.DATALINK:
case Types.DATE:
if (useJsr310DateTime) {
return "java.time.LocalDate";
}
return "Date";
case Types.DECIMAL:
return "java.math.BigDecimal";
Expand Down Expand Up @@ -64,12 +67,16 @@ public static String toJavaType(int typeCode) {
case Types.STRUCT:
return "Struct";
case Types.TIME:
return "Time";
case Types.TIME_WITH_TIMEZONE:
if(useJsr310DateTime) {
return "java.time.LocalTime";
}
return "Time";
case Types.TIMESTAMP:
return "Timestamp";
case Types.TIMESTAMP_WITH_TIMEZONE:
if(useJsr310DateTime) {
return "java.time.LocalDateTime";
}
return "Timestamp";
case Types.TINYINT:
return "Byte";
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/entityGen/entity.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ ${field.comment}
<#if requireJSR305 && !field.primitive>
<#if field.nullable>@Nullable<#else>@Nonnull</#if>
</#if>
@Column(name = "<#if jpa1Compatible>`<#else>\"</#if>${field.columnName}<#if jpa1Compatible>`<#else>\"</#if>", nullable = ${field.nullable?c})
@Column(name = "${field.columnName}", nullable = ${field.nullable?c})
private ${field.type} ${field.name}<#if field.defaultValue??> = ${field.defaultValue}</#if>;
</#list>
<#list bottomAdditionalCodeList as code>
Expand Down
8 changes: 8 additions & 0 deletions src/main/resources/entityGen/repository.ftl
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package ${packageName};

<#list importRules as rule>
import ${rule.importValue};
</#list>

public interface ${className} <#if interfaceNames.size() \gt 0>extends ${interfaceNames?join(", ")} </#if>{
}
9 changes: 9 additions & 0 deletions src/test/java/com/example/CodeGeneratorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import org.junit.runners.MethodSorters;
import com.example.unit.DatabaseUtil;

import java.io.IOException;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

Expand Down Expand Up @@ -55,4 +57,11 @@ public void _04_generateAll_TableScanMode_Is_RuleBaseduse_Jakarta_and_jsr305() t
CodeGenerator.generateAll(config, false);
}

@Test
public void _05_generateAllWithJpaRepository_useShortClassNameAsEntityName() throws Exception {
CodeGeneratorConfig config = CodeGeneratorConfig.load("entityGenConfig5.yml");
config.setUseShortClassNameAsEntityName(true);
config.setOutputDirectory("src/test/java");
CodeGenerator.generateAll(config, false);
}
}
29 changes: 29 additions & 0 deletions src/test/java/com/example/entity5/ABTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.example.entity5;

import com.example.annotation.Experimental;
import com.example.util.ExpirationPredicate;
import java.io.Serializable;
import java.sql.*;
import javax.persistence.*;
import lombok.Data;
import lombok.ToString;

/**
* Note: auto-generated by jpa-entity-generator
* TODO: This A/B testing mechanism is no longer used
*/
@Data
@ToString
@Entity(name = "ABTest")
@Table(name = "abtest")
public class ABTest implements Serializable, ExpirationPredicate {

@Id
@Column(name = "\"identifier\"", nullable = false)
private String identifier;
@Column(name = "\"expiration_timestamp\"", nullable = false)
private Integer expirationTimestamp;
@Experimental(comment = "The expected data format is JSON")
@Column(name = "\"config\"", nullable = true)
private String config;
}
30 changes: 30 additions & 0 deletions src/test/java/com/example/entity5/Blog.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.example.entity5;

import java.io.Serializable;
import java.sql.*;
import javax.persistence.*;
import lombok.Builder;
import lombok.Data;
import lombok.ToString;

/**
* Note: auto-generated by jpa-entity-generator
*/
@Data
@ToString
@Builder(toBuilder = true)
@Entity(name = "Blog")
@Table(name = "blog")
public class Blog implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "\"id\"", nullable = false)
private Integer id;
@Column(name = "\"name\"", nullable = true)
private String name;
@Column(name = "\"active\"", nullable = true)
private boolean active;
@Column(name = "\"created_at\"", nullable = false)
private Timestamp createdAt;
}
Loading