├── .gitignore
├── .travis.yml
├── src
├── test
│ ├── java
│ │ └── com
│ │ │ └── github
│ │ │ └── dcendents
│ │ │ └── mybatis
│ │ │ └── generator
│ │ │ └── plugin
│ │ │ ├── wrap
│ │ │ ├── BaseClassDTO.java
│ │ │ ├── ClassDTO.java
│ │ │ └── WrapObjectPluginTest.java
│ │ │ ├── annotation
│ │ │ └── AddClassAnnotationsPluginTest.java
│ │ │ ├── dynamic
│ │ │ └── sql
│ │ │ │ └── DynamicSqlPluginTest.java
│ │ │ ├── model
│ │ │ └── AlterModelPluginTest.java
│ │ │ ├── subpackage
│ │ │ ├── RenamePropertiesTest.java
│ │ │ └── CreateSubPackagePluginTest.java
│ │ │ ├── locking
│ │ │ └── OptimisticLockingPluginTest.java
│ │ │ └── client
│ │ │ ├── AlterResultMapPluginTest.java
│ │ │ └── CreateGenericInterfacePluginTest.java
│ └── resources
│ │ ├── log4j.xml
│ │ └── log4j.dtd
└── main
│ └── java
│ └── com
│ └── github
│ └── dcendents
│ └── mybatis
│ └── generator
│ └── plugin
│ ├── annotation
│ └── AddClassAnnotationsPlugin.java
│ ├── model
│ └── AlterModelPlugin.java
│ ├── dynamic
│ └── sql
│ │ ├── DynamicSqlPlugin.java
│ │ └── DynamicSqlSupportClassGenerator.java
│ ├── subpackage
│ ├── RenameProperties.java
│ └── CreateSubPackagePlugin.java
│ ├── locking
│ └── OptimisticLockingPlugin.java
│ ├── client
│ ├── AlterResultMapPlugin.java
│ └── CreateGenericInterfacePlugin.java
│ ├── wrap
│ └── WrapObjectPlugin.java
│ └── rename
│ └── RenameExampleClassAndMethodsPlugin.java
├── .github
└── dependabot.yml
├── pom.xml
├── LICENSE
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | .classpath
2 | .project
3 | .settings
4 | target
5 | /target-eclipse/
6 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 |
3 | jdk:
4 | - openjdk8
5 |
6 | script: mvn clean verify
7 |
8 | after_success:
9 | - bash <(curl -s https://codecov.io/bash)
10 |
--------------------------------------------------------------------------------
/src/test/java/com/github/dcendents/mybatis/generator/plugin/wrap/BaseClassDTO.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.wrap;
2 |
3 | import lombok.Getter;
4 | import lombok.Setter;
5 |
6 | public class BaseClassDTO {
7 |
8 | @Getter
9 | @Setter
10 | private String name;
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: maven
4 | directory: "/"
5 | schedule:
6 | interval: daily
7 | open-pull-requests-limit: 10
8 | target-branch: develop
9 | ignore:
10 | - dependency-name: org.mockito:mockito-core
11 | versions:
12 | - 3.7.7
13 | - 3.8.0
14 | - dependency-name: junit:junit
15 | versions:
16 | - 4.13.1
17 | - dependency-name: org.codehaus.mojo:animal-sniffer-maven-plugin
18 | versions:
19 | - "1.19"
20 |
--------------------------------------------------------------------------------
/src/test/java/com/github/dcendents/mybatis/generator/plugin/wrap/ClassDTO.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.wrap;
2 |
3 | import lombok.Getter;
4 | import lombok.Setter;
5 |
6 | public class ClassDTO extends BaseClassDTO {
7 |
8 | private String address;
9 |
10 | @Getter
11 | private String street;
12 |
13 | @Getter
14 | @Setter
15 | private String city;
16 |
17 | @Getter
18 | @Setter
19 | private String postCode;
20 |
21 | private String country;
22 |
23 | @Getter
24 | @Setter
25 | private boolean homeAddress;
26 |
27 | @Getter
28 | @Setter
29 | private Boolean workAddress;
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/resources/log4j.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dcendents/mybatis/generator/plugin/annotation/AddClassAnnotationsPlugin.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.annotation;
2 |
3 | import java.util.List;
4 |
5 | import lombok.NoArgsConstructor;
6 |
7 | import org.mybatis.generator.api.IntrospectedTable;
8 | import org.mybatis.generator.api.PluginAdapter;
9 | import org.mybatis.generator.api.dom.java.TopLevelClass;
10 |
11 | import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
12 |
13 | /**
14 | * Mybatis generator plugin to add annotations at the class level.
15 | */
16 | @NoArgsConstructor
17 | public class AddClassAnnotationsPlugin extends PluginAdapter {
18 | public static final String ANNOTATION_CLASS = "annotationClass";
19 | public static final String ANNOTATION_STRING = "annotationString";
20 |
21 | private String annotationClass;
22 | private String annotationString;
23 |
24 | @Override
25 | public boolean validate(List warnings) {
26 | annotationClass = properties.getProperty(ANNOTATION_CLASS);
27 | annotationString = properties.getProperty(ANNOTATION_STRING);
28 |
29 | String warning = "Property %s not set for plugin %s";
30 | if (!stringHasValue(annotationClass)) {
31 | warnings.add(String.format(warning, ANNOTATION_CLASS, this.getClass().getSimpleName()));
32 | }
33 | if (!stringHasValue(annotationString)) {
34 | warnings.add(String.format(warning, ANNOTATION_STRING, this.getClass().getSimpleName()));
35 | }
36 |
37 | return stringHasValue(annotationClass) && stringHasValue(annotationString);
38 | }
39 |
40 | @Override
41 | public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
42 | topLevelClass.addImportedType(annotationClass);
43 | topLevelClass.addAnnotation(annotationString);
44 |
45 | return true;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dcendents/mybatis/generator/plugin/model/AlterModelPlugin.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.model;
2 |
3 | import java.util.List;
4 | import java.util.regex.Pattern;
5 |
6 | import lombok.NoArgsConstructor;
7 |
8 | import org.mybatis.generator.api.IntrospectedTable;
9 | import org.mybatis.generator.api.PluginAdapter;
10 | import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
11 | import org.mybatis.generator.api.dom.java.TopLevelClass;
12 |
13 | import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
14 |
15 | /**
16 | * Mybatis generator plugin to modify the generated model.
17 | */
18 | @NoArgsConstructor
19 | public class AlterModelPlugin extends PluginAdapter {
20 | public static final String TABLE_NAME = "fullyQualifiedTableName";
21 | public static final String ADD_INTERFACES = "addInterfaces";
22 |
23 | private String tableName;
24 | private String[] addInterfaces;
25 |
26 | @Override
27 | public boolean validate(List warnings) {
28 | tableName = properties.getProperty(TABLE_NAME);
29 | String interfacesString = properties.getProperty(ADD_INTERFACES);
30 |
31 | String warning = "Property %s not set for plugin %s";
32 | if (!stringHasValue(tableName)) {
33 | warnings.add(String.format(warning, TABLE_NAME, this.getClass().getSimpleName()));
34 | }
35 | if (!stringHasValue(interfacesString)) {
36 | warnings.add(String.format(warning, ADD_INTERFACES, this.getClass().getSimpleName()));
37 | } else {
38 | addInterfaces = interfacesString.split(",");
39 | }
40 |
41 | return stringHasValue(tableName) && addInterfaces != null;
42 | }
43 |
44 | private boolean tableMatches(IntrospectedTable introspectedTable) {
45 | return tableName.equals(introspectedTable.getFullyQualifiedTableNameAtRuntime())
46 | || Pattern.matches(tableName, introspectedTable.getFullyQualifiedTableNameAtRuntime());
47 | }
48 |
49 | @Override
50 | public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
51 | if (tableMatches(introspectedTable)) {
52 | for (String theInterface : addInterfaces) {
53 | FullyQualifiedJavaType type = new FullyQualifiedJavaType(theInterface);
54 | topLevelClass.addImportedType(type);
55 | topLevelClass.addSuperInterface(type);
56 | }
57 | }
58 |
59 | return true;
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dcendents/mybatis/generator/plugin/dynamic/sql/DynamicSqlPlugin.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.dynamic.sql;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import lombok.NoArgsConstructor;
7 |
8 | import org.apache.commons.lang3.StringUtils;
9 | import org.mybatis.generator.api.GeneratedJavaFile;
10 | import org.mybatis.generator.api.IntrospectedTable;
11 | import org.mybatis.generator.api.PluginAdapter;
12 | import org.mybatis.generator.api.dom.DefaultJavaFormatter;
13 | import org.mybatis.generator.api.dom.java.CompilationUnit;
14 |
15 | /**
16 | * Mybatis generator plugin to add dynamic sql table definitions.
17 | */
18 | @NoArgsConstructor
19 | public class DynamicSqlPlugin extends PluginAdapter {
20 | public static final String TABLE_CLASS_SUFFIX = "tableClassSuffix";
21 | public static final String ADD_ALIASED_COLUMNS = "addAliasedColumns";
22 | public static final String ADD_TABLE_ALIAS = "addTableAlias";
23 | public static final String TABLE_ALIAS_FIELD_NAME = "tableAliasFieldName";
24 |
25 | public static final String DEFAULT_TABLE_ALIAS_FIELD = "tableAlias";
26 |
27 | private String tableClassSuffix;
28 | private boolean addAliasedColumns;
29 | private boolean addTableAlias;
30 | private String tableAliasFieldName;
31 |
32 | @Override
33 | public boolean validate(List warnings) {
34 | tableClassSuffix = properties.getProperty(TABLE_CLASS_SUFFIX);
35 | String addAliasedColumnsString = properties.getProperty(ADD_ALIASED_COLUMNS);
36 | String addTableAliasString = properties.getProperty(ADD_TABLE_ALIAS);
37 | tableAliasFieldName = properties.getProperty(TABLE_ALIAS_FIELD_NAME);
38 |
39 | tableClassSuffix = tableClassSuffix == null ? "" : tableClassSuffix.trim();
40 | addAliasedColumns = Boolean.parseBoolean(addAliasedColumnsString);
41 | addTableAlias = Boolean.parseBoolean(addTableAliasString);
42 | if (StringUtils.isBlank(tableAliasFieldName)) {
43 | tableAliasFieldName = DEFAULT_TABLE_ALIAS_FIELD;
44 | }
45 |
46 | return true;
47 | }
48 |
49 | @Override
50 | public List contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
51 | List models = new ArrayList<>();
52 |
53 | CompilationUnit unit = DynamicSqlSupportClassGenerator
54 | .of(introspectedTable, context.getCommentGenerator(), tableClassSuffix, addAliasedColumns, addTableAlias, tableAliasFieldName, properties)
55 | .generate();
56 |
57 | GeneratedJavaFile dynamicSqlModel =
58 | new GeneratedJavaFile(unit, context.getJavaClientGeneratorConfiguration().getTargetProject(), new DefaultJavaFormatter());
59 |
60 | models.add(dynamicSqlModel);
61 |
62 | return models;
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dcendents/mybatis/generator/plugin/subpackage/RenameProperties.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.subpackage;
2 |
3 | import java.util.List;
4 |
5 | import org.apache.commons.lang3.StringUtils;
6 | import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
7 | import org.mybatis.generator.api.dom.xml.Attribute;
8 |
9 | import lombok.AccessLevel;
10 | import lombok.Getter;
11 | import lombok.NoArgsConstructor;
12 | import lombok.Setter;
13 | import lombok.extern.slf4j.Slf4j;
14 |
15 | @NoArgsConstructor
16 | @Getter(AccessLevel.PACKAGE)
17 | @Setter(AccessLevel.PACKAGE)
18 | @Slf4j
19 | public class RenameProperties {
20 |
21 | private static final String DOT = ".";
22 |
23 | private boolean enabled;
24 |
25 | private String subPpackage;
26 | private String classSuffix;
27 |
28 | private String originalType;
29 | private String newType;
30 |
31 | public void validate(String theSubPpackage, String theClassSuffix) {
32 | enabled = theSubPpackage != null || theClassSuffix != null;
33 |
34 | if (enabled) {
35 | if (theSubPpackage == null) {
36 | subPpackage = StringUtils.EMPTY;
37 | } else if (!theSubPpackage.startsWith(DOT)) {
38 | subPpackage = DOT + theSubPpackage;
39 | } else {
40 | subPpackage = theSubPpackage;
41 | }
42 |
43 | classSuffix = theClassSuffix == null ? StringUtils.EMPTY : theClassSuffix;
44 | }
45 | }
46 |
47 | public String setTypes(String theOriginalType) {
48 | if (enabled) {
49 | this.originalType = theOriginalType;
50 | int lastDot = originalType.lastIndexOf(DOT);
51 | newType = originalType.substring(0, lastDot) + subPpackage + originalType.substring(lastDot) + classSuffix;
52 | log.debug("replace type [{}][{}]", originalType, newType);
53 | return newType;
54 | }
55 |
56 | return theOriginalType;
57 | }
58 |
59 | public FullyQualifiedJavaType renameType(FullyQualifiedJavaType theJavaType) {
60 | if (theJavaType.getFullyQualifiedName().contains(newType)) {
61 | log.debug("set new return type: [{}][{}]", newType, originalType);
62 | return new FullyQualifiedJavaType(theJavaType.getFullyQualifiedName().replace(newType, originalType));
63 | } else {
64 | return theJavaType;
65 | }
66 | }
67 |
68 | public Attribute renameAttribute(Attribute attribute) {
69 | if (newType.equals(attribute.getValue())) {
70 | log.debug("set new model attribute: [{}][{}][{}]", attribute.getName(), newType, originalType);
71 | return new Attribute(attribute.getName(), originalType);
72 | } else {
73 | return attribute;
74 | }
75 | }
76 |
77 | public void renameAnnotations(List lines) {
78 | if (lines != null) {
79 | for (int i = 0; i < lines.size(); i++) {
80 | String line = lines.get(i);
81 | while (line.contains(newType)) {
82 | line = line.replace(newType, originalType);
83 | log.debug("set new annotation line: [{}] -> [{}]", lines.get(i), line);
84 | lines.set(i, line);
85 | }
86 | }
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/test/java/com/github/dcendents/mybatis/generator/plugin/annotation/AddClassAnnotationsPluginTest.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.annotation;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 | import static org.mockito.Matchers.eq;
5 | import static org.mockito.Mockito.verify;
6 |
7 | import java.util.ArrayList;
8 | import java.util.List;
9 |
10 | import org.junit.Before;
11 | import org.junit.Test;
12 | import org.junit.runner.RunWith;
13 | import org.mockito.Mock;
14 | import org.mockito.runners.MockitoJUnitRunner;
15 | import org.mybatis.generator.api.dom.java.TopLevelClass;
16 |
17 | /**
18 | * Tests for the class AddClassAnnotationsPlugin.
19 | */
20 | @RunWith(MockitoJUnitRunner.class)
21 | public class AddClassAnnotationsPluginTest {
22 |
23 | private AddClassAnnotationsPlugin plugin;
24 |
25 | @Mock
26 | private TopLevelClass topLevelClass;
27 |
28 | @Before
29 | public void init() {
30 | plugin = new AddClassAnnotationsPlugin();
31 | }
32 |
33 | @Test
34 | public void shouldBeInvalidWithoutAnyPropertyConfigured() {
35 | // Given
36 |
37 | // When
38 | List warnings = new ArrayList<>();
39 | boolean ok = plugin.validate(warnings);
40 |
41 | // Then
42 | assertThat(ok).isFalse();
43 | assertThat(warnings).hasSize(2);
44 | }
45 |
46 | @Test
47 | public void shouldBeInvalidWithOnlyTheClassConfigured() {
48 | // Given
49 | plugin.getProperties().put(AddClassAnnotationsPlugin.ANNOTATION_CLASS, Test.class.getName());
50 |
51 | // When
52 | List warnings = new ArrayList<>();
53 | boolean ok = plugin.validate(warnings);
54 |
55 | // Then
56 | assertThat(ok).isFalse();
57 | assertThat(warnings).hasSize(1);
58 | }
59 |
60 | @Test
61 | public void shouldBeInvalidWithOnlyTheAnnotationConfigured() {
62 | // Given
63 | plugin.getProperties().put(AddClassAnnotationsPlugin.ANNOTATION_STRING, "@Test");
64 |
65 | // When
66 | List warnings = new ArrayList<>();
67 | boolean ok = plugin.validate(warnings);
68 |
69 | // Then
70 | assertThat(ok).isFalse();
71 | assertThat(warnings).hasSize(1);
72 | }
73 |
74 | @Test
75 | public void shouldBeValidWhenBothPropertiesAreConfigured() {
76 | // Given
77 | plugin.getProperties().put(AddClassAnnotationsPlugin.ANNOTATION_CLASS, Test.class.getName());
78 | plugin.getProperties().put(AddClassAnnotationsPlugin.ANNOTATION_STRING, "@Test");
79 |
80 | // When
81 | List warnings = new ArrayList<>();
82 | boolean ok = plugin.validate(warnings);
83 |
84 | // Then
85 | assertThat(ok).isTrue();
86 | assertThat(warnings).isEmpty();
87 | }
88 |
89 | @Test
90 | public void shouldAddTheAnnotation() {
91 | // Given
92 | plugin.getProperties().put(AddClassAnnotationsPlugin.ANNOTATION_CLASS, Test.class.getName());
93 | plugin.getProperties().put(AddClassAnnotationsPlugin.ANNOTATION_STRING, "@Test");
94 |
95 | List warnings = new ArrayList<>();
96 | plugin.validate(warnings);
97 |
98 | // When
99 | boolean ok = plugin.modelBaseRecordClassGenerated(topLevelClass, null);
100 |
101 | // Then
102 | assertThat(ok).isTrue();
103 | verify(topLevelClass).addImportedType(eq(plugin.getProperties().get(AddClassAnnotationsPlugin.ANNOTATION_CLASS).toString()));
104 | verify(topLevelClass).addAnnotation(eq(plugin.getProperties().get(AddClassAnnotationsPlugin.ANNOTATION_STRING).toString()));
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dcendents/mybatis/generator/plugin/locking/OptimisticLockingPlugin.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.locking;
2 |
3 | import java.util.List;
4 | import java.util.regex.Pattern;
5 |
6 | import lombok.NoArgsConstructor;
7 |
8 | import org.apache.commons.lang3.StringUtils;
9 | import org.mybatis.generator.api.IntrospectedColumn;
10 | import org.mybatis.generator.api.IntrospectedTable;
11 | import org.mybatis.generator.api.PluginAdapter;
12 | import org.mybatis.generator.api.dom.java.Interface;
13 | import org.mybatis.generator.api.dom.java.Method;
14 | import org.mybatis.generator.api.dom.java.TopLevelClass;
15 |
16 | import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
17 |
18 | /**
19 | * Mybatis generator plugin to add update statements with optimistic locking.
20 | */
21 | @NoArgsConstructor
22 | public class OptimisticLockingPlugin extends PluginAdapter {
23 | public static final String TABLE_NAME = "fullyQualifiedTableName";
24 | public static final String LOCK_COLUMN = "lockColumn";
25 | public static final String LOCK_COLUMN_FUNCTION = "lockColumnFunction";
26 |
27 | private String tableName;
28 | private String lockColumn;
29 | private String lockColumnFunction;
30 |
31 | static final String METHOD_SUFFIX = "WithOptimisticLocking";
32 |
33 | @Override
34 | public boolean validate(List warnings) {
35 | tableName = properties.getProperty(TABLE_NAME);
36 | lockColumn = properties.getProperty(LOCK_COLUMN);
37 | lockColumnFunction = properties.getProperty(LOCK_COLUMN_FUNCTION);
38 |
39 | String warning = "Property %s not set for plugin %s";
40 | if (!stringHasValue(tableName)) {
41 | warnings.add(String.format(warning, TABLE_NAME, this.getClass().getSimpleName()));
42 | }
43 | if (!stringHasValue(lockColumn)) {
44 | warnings.add(String.format(warning, LOCK_COLUMN, this.getClass().getSimpleName()));
45 | }
46 |
47 | if (StringUtils.isBlank(lockColumnFunction)) {
48 | lockColumnFunction = lockColumn;
49 | }
50 |
51 | return stringHasValue(tableName) && stringHasValue(lockColumn);
52 | }
53 |
54 | boolean tableMatches(IntrospectedTable introspectedTable) {
55 | return tableName.equals(introspectedTable.getFullyQualifiedTableNameAtRuntime())
56 | || Pattern.matches(tableName, introspectedTable.getFullyQualifiedTableNameAtRuntime());
57 | }
58 |
59 | @Override
60 | public boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
61 | if (tableMatches(introspectedTable)) {
62 | Method withLock = addMethod(method, introspectedTable);
63 | interfaze.addMethod(withLock);
64 | }
65 |
66 | return true;
67 | }
68 |
69 | @Override
70 | public boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
71 | if (tableMatches(introspectedTable)) {
72 | Method withLock = addMethod(method, introspectedTable);
73 | topLevelClass.addMethod(withLock);
74 | }
75 |
76 | return true;
77 | }
78 |
79 | Method addMethod(Method method, IntrospectedTable introspectedTable) {
80 | IntrospectedColumn column = getColumn(introspectedTable);
81 |
82 | Method withLock = new Method(method);
83 | withLock.setName(method.getName() + METHOD_SUFFIX);
84 |
85 | withLock.getAnnotations().clear();
86 |
87 | for (String line : method.getAnnotations()) {
88 | if (line.matches("\\s*\".*\"\\s*")) {
89 | withLock.getAnnotations().add(line + ",");
90 |
91 | String typeHandler = column.getTypeHandler() != null ? String.format(",typeHandler=%s", column.getTypeHandler()) : "";
92 | withLock.getAnnotations().add(String.format(" \"and %1$s = #{%2$s,jdbcType=%3$s%4$s}\"", lockColumnFunction,
93 | column.getJavaProperty(), column.getJdbcTypeName(), typeHandler));
94 | } else {
95 | withLock.getAnnotations().add(line);
96 | }
97 | }
98 |
99 | return withLock;
100 | }
101 |
102 | IntrospectedColumn getColumn(IntrospectedTable introspectedTable) {
103 | for (IntrospectedColumn column : introspectedTable.getAllColumns()) {
104 | if (lockColumn.equals(column.getActualColumnName())) {
105 | return column;
106 | }
107 | }
108 |
109 | return null;
110 | }
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/src/test/java/com/github/dcendents/mybatis/generator/plugin/dynamic/sql/DynamicSqlPluginTest.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.dynamic.sql;
2 |
3 | import static org.assertj.core.api.BDDAssertions.then;
4 | import static org.mockito.BDDMockito.given;
5 |
6 | import java.util.ArrayList;
7 | import java.util.Arrays;
8 | import java.util.List;
9 | import java.util.Properties;
10 |
11 | import org.junit.Before;
12 | import org.junit.Test;
13 | import org.junit.runner.RunWith;
14 | import org.mockito.Mock;
15 | import org.mockito.runners.MockitoJUnitRunner;
16 | import org.mybatis.generator.api.CommentGenerator;
17 | import org.mybatis.generator.api.FullyQualifiedTable;
18 | import org.mybatis.generator.api.GeneratedJavaFile;
19 | import org.mybatis.generator.api.IntrospectedColumn;
20 | import org.mybatis.generator.api.IntrospectedTable;
21 | import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
22 | import org.mybatis.generator.config.Context;
23 | import org.mybatis.generator.config.JavaClientGeneratorConfiguration;
24 |
25 | /**
26 | * Tests for the class DynamicSqlPlugin.
27 | */
28 | @RunWith(MockitoJUnitRunner.class)
29 | public class DynamicSqlPluginTest {
30 |
31 | private DynamicSqlPlugin plugin;
32 |
33 | @Mock
34 | private IntrospectedTable table;
35 | @Mock
36 | private FullyQualifiedTable tableName;
37 |
38 | @Mock
39 | private IntrospectedColumn column1;
40 | @Mock
41 | private IntrospectedColumn column2;
42 |
43 | @Mock
44 | private Context context;
45 | @Mock
46 | private CommentGenerator commentGenerator;
47 | @Mock
48 | private JavaClientGeneratorConfiguration javaClientGeneratorConfiguration;
49 |
50 | @Before
51 | public void init() {
52 | given(context.getCommentGenerator()).willReturn(commentGenerator);
53 | given(context.getJavaClientGeneratorConfiguration()).willReturn(javaClientGeneratorConfiguration);
54 |
55 | given(javaClientGeneratorConfiguration.getTargetProject()).willReturn("src/main/java");
56 |
57 | given(tableName.getAlias()).willReturn("alias");
58 |
59 | given(table.getFullyQualifiedTable()).willReturn(tableName);
60 | given(table.getFullyQualifiedTableNameAtRuntime()).willReturn("table_name");
61 | given(table.getMyBatis3JavaMapperType()).willReturn("some.package.JavaMapperType");
62 | given(table.getBaseRecordType()).willReturn("some.package.BaseRecordType");
63 | given(table.getAllColumns()).willReturn(Arrays.asList(column1, column2));
64 |
65 | given(column1.getFullyQualifiedJavaType()).willReturn(new FullyQualifiedJavaType("int"));
66 | given(column1.getTableAlias()).willReturn("a");
67 |
68 | given(column2.getFullyQualifiedJavaType()).willReturn(new FullyQualifiedJavaType("java.util.Calendar"));
69 | given(column2.getTypeHandler()).willReturn("type.Handler");
70 |
71 | plugin = new DynamicSqlPlugin();
72 | plugin.setContext(context);
73 |
74 | Properties properties = new Properties();
75 | properties.put(DynamicSqlPlugin.TABLE_CLASS_SUFFIX, "Table");
76 | properties.put(DynamicSqlPlugin.ADD_ALIASED_COLUMNS, "true");
77 | properties.put(DynamicSqlPlugin.ADD_TABLE_ALIAS, "true");
78 | properties.put("table_name.otherAlias", "ot");
79 | plugin.setProperties(properties);
80 | plugin.validate(new ArrayList());
81 | }
82 |
83 | @Test
84 | public void shouldBeValidWithoutAnyPropertyConfigured() {
85 | // Given
86 | plugin = new DynamicSqlPlugin();
87 |
88 | // When
89 | List warnings = new ArrayList<>();
90 | boolean ok = plugin.validate(warnings);
91 |
92 | // Then
93 | then(ok).isTrue();
94 | then(warnings).isEmpty();
95 | }
96 |
97 | @Test
98 | public void shouldBeValidWithPropertiesConfigured() {
99 | // Given
100 |
101 | // When
102 | List warnings = new ArrayList<>();
103 | boolean ok = plugin.validate(warnings);
104 |
105 | // Then
106 | then(ok).isTrue();
107 | then(warnings).isEmpty();
108 | }
109 |
110 | @Test
111 | public void shouldGenerateAdditionalFile() throws Exception {
112 | // Given
113 |
114 | // When
115 | List files = plugin.contextGenerateAdditionalJavaFiles(table);
116 |
117 | // Then
118 | then(files).hasSize(1);
119 | }
120 |
121 | @Test
122 | public void shouldGenerateAdditionalFileEvenWhenTableHasNoColumns() throws Exception {
123 | // Given
124 | given(table.getAllColumns()).willReturn(new ArrayList());
125 |
126 | // When
127 | List files = plugin.contextGenerateAdditionalJavaFiles(table);
128 |
129 | // Then
130 | then(files).hasSize(1);
131 | }
132 |
133 | }
134 |
--------------------------------------------------------------------------------
/src/test/java/com/github/dcendents/mybatis/generator/plugin/model/AlterModelPluginTest.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.model;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 | import static org.mockito.BDDMockito.given;
5 | import static org.mockito.Matchers.any;
6 | import static org.mockito.Mockito.times;
7 | import static org.mockito.Mockito.verify;
8 |
9 | import java.io.Serializable;
10 | import java.util.ArrayList;
11 | import java.util.List;
12 |
13 | import org.junit.Before;
14 | import org.junit.Test;
15 | import org.junit.runner.RunWith;
16 | import org.mockito.ArgumentCaptor;
17 | import org.mockito.Mock;
18 | import org.mockito.runners.MockitoJUnitRunner;
19 | import org.mybatis.generator.api.IntrospectedTable;
20 | import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
21 | import org.mybatis.generator.api.dom.java.TopLevelClass;
22 |
23 | /**
24 | * Tests for the class AlterModelPlugin.
25 | */
26 | @RunWith(MockitoJUnitRunner.class)
27 | public class AlterModelPluginTest {
28 |
29 | private AlterModelPlugin plugin;
30 |
31 | @Mock
32 | private IntrospectedTable introspectedTable;
33 | @Mock
34 | private TopLevelClass topLevelClass;
35 |
36 | private static final String TABLE_NAME = "table_name";
37 |
38 | @Before
39 | public void init() throws Exception {
40 | plugin = new AlterModelPlugin();
41 | plugin.getProperties().put(AlterModelPlugin.TABLE_NAME, TABLE_NAME);
42 | plugin.getProperties().put(AlterModelPlugin.ADD_INTERFACES, Serializable.class.getName());
43 | plugin.validate(new ArrayList());
44 | }
45 |
46 | @Test
47 | public void shouldBeInvalidWithoutAnyPropertyConfigured() {
48 | // Given
49 | AlterModelPlugin instance = new AlterModelPlugin();
50 |
51 | // When
52 | List warnings = new ArrayList<>();
53 | boolean ok = instance.validate(warnings);
54 |
55 | // Then
56 | assertThat(ok).isFalse();
57 | assertThat(warnings).hasSize(2);
58 | }
59 |
60 | @Test
61 | public void shouldBeInvalidWithOnlyTheTableNameConfigured() {
62 | // Given
63 | AlterModelPlugin instance = new AlterModelPlugin();
64 | instance.getProperties().put(AlterModelPlugin.TABLE_NAME, TABLE_NAME);
65 |
66 | // When
67 | List warnings = new ArrayList<>();
68 | boolean ok = instance.validate(warnings);
69 |
70 | // Then
71 | assertThat(ok).isFalse();
72 | assertThat(warnings).hasSize(1);
73 | }
74 |
75 | @Test
76 | public void shouldBeInvalidWithOnlyTheInterfacesConfigured() {
77 | // Given
78 | AlterModelPlugin instance = new AlterModelPlugin();
79 | instance.getProperties().put(AlterModelPlugin.ADD_INTERFACES, Serializable.class.getName());
80 |
81 | // When
82 | List warnings = new ArrayList<>();
83 | boolean ok = instance.validate(warnings);
84 |
85 | // Then
86 | assertThat(ok).isFalse();
87 | assertThat(warnings).hasSize(1);
88 | }
89 |
90 | @Test
91 | public void shouldBeValidWhenBothPropertiesAreConfigured() {
92 | // Given
93 | AlterModelPlugin instance = new AlterModelPlugin();
94 | instance.getProperties().put(AlterModelPlugin.TABLE_NAME, TABLE_NAME);
95 | instance.getProperties().put(AlterModelPlugin.ADD_INTERFACES, Serializable.class.getName());
96 |
97 | // When
98 | List warnings = new ArrayList<>();
99 | boolean ok = instance.validate(warnings);
100 |
101 | // Then
102 | assertThat(ok).isTrue();
103 | assertThat(warnings).isEmpty();
104 | }
105 |
106 | @Test
107 | public void shouldNotModifyModelBaseRecordClassIfTableDoesNotMatch() throws Exception {
108 | // Given
109 | given(introspectedTable.getFullyQualifiedTableNameAtRuntime()).willReturn("wrong_name");
110 |
111 | // When
112 | boolean ok = plugin.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
113 |
114 | // Then
115 | assertThat(ok).isTrue();
116 | verify(topLevelClass, times(0)).addImportedType(any(FullyQualifiedJavaType.class));
117 | verify(topLevelClass, times(0)).addSuperInterface(any(FullyQualifiedJavaType.class));
118 | }
119 |
120 | @Test
121 | public void shouldAddInterfacesToModelBaseRecordClass() throws Exception {
122 | // Given
123 | given(introspectedTable.getFullyQualifiedTableNameAtRuntime()).willReturn(TABLE_NAME);
124 |
125 | // When
126 | boolean ok = plugin.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
127 |
128 | // Then
129 | assertThat(ok).isTrue();
130 |
131 | ArgumentCaptor typeCaptor = ArgumentCaptor.forClass(FullyQualifiedJavaType.class);
132 |
133 | verify(topLevelClass).addImportedType(typeCaptor.capture());
134 | FullyQualifiedJavaType importedType = typeCaptor.getValue();
135 | verify(topLevelClass).addSuperInterface(typeCaptor.capture());
136 | FullyQualifiedJavaType interfaceType = typeCaptor.getValue();
137 |
138 | assertThat(importedType).isNotNull();
139 | assertThat(interfaceType).isNotNull();
140 |
141 | assertThat(importedType).isSameAs(interfaceType);
142 | assertThat(importedType.getFullyQualifiedName()).isEqualTo(Serializable.class.getName());
143 | }
144 |
145 | @Test
146 | public void shouldAcceptRegexValueForTableName() throws Exception {
147 | // Given
148 | given(introspectedTable.getFullyQualifiedTableNameAtRuntime()).willReturn(TABLE_NAME);
149 | plugin.getProperties().put(AlterModelPlugin.TABLE_NAME, TABLE_NAME.substring(0, 3) + ".*");
150 | plugin.validate(new ArrayList());
151 |
152 | // When
153 | boolean ok = plugin.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
154 |
155 | // Then
156 | assertThat(ok).isTrue();
157 | verify(topLevelClass).addImportedType(any(FullyQualifiedJavaType.class));
158 | verify(topLevelClass).addSuperInterface(any(FullyQualifiedJavaType.class));
159 | }
160 |
161 | }
162 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dcendents/mybatis/generator/plugin/client/AlterResultMapPlugin.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.client;
2 |
3 | import java.util.List;
4 | import java.util.regex.Pattern;
5 |
6 | import lombok.NoArgsConstructor;
7 |
8 | import org.mybatis.generator.api.IntrospectedTable;
9 | import org.mybatis.generator.api.PluginAdapter;
10 | import org.mybatis.generator.api.dom.java.Interface;
11 | import org.mybatis.generator.api.dom.java.Method;
12 | import org.mybatis.generator.api.dom.java.TopLevelClass;
13 | import org.mybatis.generator.api.dom.xml.Attribute;
14 | import org.mybatis.generator.api.dom.xml.XmlElement;
15 |
16 | import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
17 |
18 | /**
19 | * Mybatis generator plugin to alter the id of the result map returned by all the select methods.
20 | */
21 | @NoArgsConstructor
22 | public class AlterResultMapPlugin extends PluginAdapter {
23 | public static final String TABLE_NAME = "fullyQualifiedTableName";
24 | public static final String RESULT_MAP_ID = "resultMapId";
25 |
26 | private String tableName;
27 | private String resultMapId;
28 |
29 | static final String RESULT_MAP_ATTRIBUTE = "resultMap";
30 | static final Pattern ANNOTATION_PATTERN = Pattern.compile("@ResultMap\\(\".*\"\\)");
31 | static final String ANNOTATION_FORMAT = "@ResultMap(\"%s\")";
32 |
33 | @Override
34 | public boolean validate(List warnings) {
35 | tableName = properties.getProperty(TABLE_NAME);
36 | resultMapId = properties.getProperty(RESULT_MAP_ID);
37 |
38 | String warning = "Property %s not set for plugin %s";
39 | if (!stringHasValue(tableName)) {
40 | warnings.add(String.format(warning, TABLE_NAME, this.getClass().getSimpleName()));
41 | }
42 | if (!stringHasValue(resultMapId)) {
43 | warnings.add(String.format(warning, RESULT_MAP_ID, this.getClass().getSimpleName()));
44 | }
45 |
46 | return stringHasValue(tableName) && stringHasValue(resultMapId);
47 | }
48 |
49 | private boolean tableMatches(IntrospectedTable introspectedTable) {
50 | return tableName.equals(introspectedTable.getFullyQualifiedTableNameAtRuntime());
51 | }
52 |
53 | void renameResultMapAttribute(XmlElement element, IntrospectedTable introspectedTable) {
54 | if (tableMatches(introspectedTable)) {
55 | List attributes = element.getAttributes();
56 |
57 | for (int i = 0; i < attributes.size(); i++) {
58 | Attribute attribute = attributes.get(i);
59 | if (RESULT_MAP_ATTRIBUTE.equals(attribute.getName())) {
60 | Attribute newAtt = new Attribute(RESULT_MAP_ATTRIBUTE, resultMapId);
61 | attributes.remove(i);
62 | attributes.add(newAtt);
63 | break;
64 | }
65 | }
66 | }
67 | }
68 |
69 | void renameResultMapAttribute(Method method, IntrospectedTable introspectedTable) {
70 | if (tableMatches(introspectedTable)) {
71 | List annotations = method.getAnnotations();
72 |
73 | for (int i = 0; i < annotations.size(); i++) {
74 | String annotation = annotations.get(i);
75 | if (ANNOTATION_PATTERN.matcher(annotation).matches()) {
76 | String newAnnotation = String.format(ANNOTATION_FORMAT, resultMapId);
77 | annotations.remove(i);
78 | annotations.add(newAnnotation);
79 | break;
80 | }
81 | }
82 | }
83 | }
84 |
85 | @Override
86 | public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element,
87 | IntrospectedTable introspectedTable) {
88 | renameResultMapAttribute(element, introspectedTable);
89 |
90 | return true;
91 | }
92 |
93 | @Override
94 | public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element,
95 | IntrospectedTable introspectedTable) {
96 | renameResultMapAttribute(element, introspectedTable);
97 |
98 | return true;
99 | }
100 |
101 | @Override
102 | public boolean sqlMapSelectByPrimaryKeyElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
103 | renameResultMapAttribute(element, introspectedTable);
104 |
105 | return true;
106 | }
107 |
108 | @Override
109 | public boolean sqlMapSelectAllElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
110 | renameResultMapAttribute(element, introspectedTable);
111 |
112 | return true;
113 | }
114 |
115 | @Override
116 | public boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze,
117 | IntrospectedTable introspectedTable) {
118 | renameResultMapAttribute(method, introspectedTable);
119 |
120 | return true;
121 | }
122 |
123 | @Override
124 | public boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method, TopLevelClass topLevelClass,
125 | IntrospectedTable introspectedTable) {
126 | renameResultMapAttribute(method, introspectedTable);
127 |
128 | return true;
129 | }
130 |
131 | @Override
132 | public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze,
133 | IntrospectedTable introspectedTable) {
134 | renameResultMapAttribute(method, introspectedTable);
135 |
136 | return true;
137 | }
138 |
139 | @Override
140 | public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method, TopLevelClass topLevelClass,
141 | IntrospectedTable introspectedTable) {
142 | renameResultMapAttribute(method, introspectedTable);
143 |
144 | return true;
145 | }
146 |
147 | @Override
148 | public boolean clientSelectByPrimaryKeyMethodGenerated(Method method, Interface interfaze,
149 | IntrospectedTable introspectedTable) {
150 | renameResultMapAttribute(method, introspectedTable);
151 |
152 | return true;
153 | }
154 |
155 | @Override
156 | public boolean clientSelectByPrimaryKeyMethodGenerated(Method method, TopLevelClass topLevelClass,
157 | IntrospectedTable introspectedTable) {
158 | renameResultMapAttribute(method, introspectedTable);
159 |
160 | return true;
161 | }
162 |
163 | @Override
164 | public boolean clientSelectAllMethodGenerated(Method method, Interface interfaze,
165 | IntrospectedTable introspectedTable) {
166 | renameResultMapAttribute(method, introspectedTable);
167 |
168 | return true;
169 | }
170 |
171 | @Override
172 | public boolean clientSelectAllMethodGenerated(Method method, TopLevelClass topLevelClass,
173 | IntrospectedTable introspectedTable) {
174 | renameResultMapAttribute(method, introspectedTable);
175 |
176 | return true;
177 | }
178 |
179 | }
180 |
--------------------------------------------------------------------------------
/src/test/java/com/github/dcendents/mybatis/generator/plugin/subpackage/RenamePropertiesTest.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.subpackage;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | import org.apache.commons.lang3.StringUtils;
9 | import org.junit.Before;
10 | import org.junit.Test;
11 | import org.junit.runner.RunWith;
12 | import org.mockito.runners.MockitoJUnitRunner;
13 | import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
14 | import org.mybatis.generator.api.dom.xml.Attribute;
15 |
16 | /**
17 | * Tests for the class RenameProperties.
18 | */
19 | @RunWith(MockitoJUnitRunner.class)
20 | public class RenamePropertiesTest {
21 |
22 | private static final String SUB_PACKAGE = ".sub";
23 | private static final String SUFFIX = "Suffix";
24 | private static final String ORIGINAL_TYPE = "some.package.Type";
25 | private static final String NEW_TYPE = "some.package.sub.TypeSuffix";
26 |
27 | private RenameProperties brandNew;
28 | private RenameProperties disabled;
29 | private RenameProperties initializedBoth;
30 | private RenameProperties allSet;
31 |
32 | @Before
33 | public void init() throws Exception {
34 | brandNew = new RenameProperties();
35 |
36 | disabled = new RenameProperties();
37 | disabled.setEnabled(false);
38 |
39 | initializedBoth = new RenameProperties();
40 | initializedBoth.setEnabled(true);
41 | initializedBoth.setSubPpackage(SUB_PACKAGE);
42 | initializedBoth.setClassSuffix(SUFFIX);
43 |
44 | allSet = new RenameProperties();
45 | allSet.setEnabled(true);
46 | allSet.setSubPpackage(SUB_PACKAGE);
47 | allSet.setClassSuffix(SUFFIX);
48 | allSet.setOriginalType(ORIGINAL_TYPE);
49 | allSet.setNewType(NEW_TYPE);
50 | }
51 |
52 | @Test
53 | public void shouldBeDisabledWhenBothParametersAreNull() throws Exception {
54 | // Given
55 |
56 | // When
57 | brandNew.validate(null, null);
58 |
59 | // Then
60 | assertThat(brandNew.isEnabled()).isFalse();
61 | }
62 |
63 | @Test
64 | public void shouldInitializeSubPAckageToEmptyStringWhenNull() throws Exception {
65 | // Given
66 |
67 | // When
68 | brandNew.validate(null, "suffix");
69 |
70 | // Then
71 | assertThat(brandNew.isEnabled()).isTrue();
72 | assertThat(brandNew.getSubPpackage()).isEqualTo(StringUtils.EMPTY);
73 | }
74 |
75 | @Test
76 | public void shouldInitializeClassSuffixToEmptyStringWhenNull() throws Exception {
77 | RenameProperties props = new RenameProperties();
78 |
79 | // Given
80 |
81 | // When
82 | props.validate("package", null);
83 |
84 | // Then
85 | assertThat(props.isEnabled()).isTrue();
86 | assertThat(props.getClassSuffix()).isEqualTo(StringUtils.EMPTY);
87 | }
88 |
89 | @Test
90 | public void shouldPrefixSubPAckageWithDotWhenMissing() throws Exception {
91 | // Given
92 |
93 | // When
94 | brandNew.validate("package", "suffix");
95 |
96 | // Then
97 | assertThat(brandNew.isEnabled()).isTrue();
98 | assertThat(brandNew.getSubPpackage()).isEqualTo(".package");
99 | }
100 |
101 | @Test
102 | public void shouldNotPrefixSubPAckageWithDotWhenPresent() throws Exception {
103 | // Given
104 |
105 | // When
106 | brandNew.validate(".package", "suffix");
107 |
108 | // Then
109 | assertThat(brandNew.isEnabled()).isTrue();
110 | assertThat(brandNew.getSubPpackage()).isEqualTo(".package");
111 | }
112 |
113 | @Test
114 | public void shouldReturnOriginalTypeWhenDisabled() throws Exception {
115 | // Given
116 | String type = "type";
117 |
118 | // When
119 | String renamed = disabled.setTypes(type);
120 |
121 | // Then
122 | assertThat(renamed).isSameAs(type);
123 | }
124 |
125 | @Test
126 | public void shouldRenameType() throws Exception {
127 | // Given
128 |
129 | // When
130 | String renamed = initializedBoth.setTypes(ORIGINAL_TYPE);
131 |
132 | // Then
133 | assertThat(renamed).isEqualTo(NEW_TYPE);
134 | assertThat(initializedBoth.getOriginalType()).isEqualTo(ORIGINAL_TYPE);
135 | assertThat(initializedBoth.getNewType()).isEqualTo(renamed);
136 | }
137 |
138 | @Test
139 | public void shouldNotRenameTypesThatDontMatch() throws Exception {
140 | // Given
141 | String type = "some.other.Type";
142 | FullyQualifiedJavaType javaType = new FullyQualifiedJavaType(type);
143 |
144 | // When
145 | FullyQualifiedJavaType renamed = allSet.renameType(javaType);
146 |
147 | // Then
148 | assertThat(renamed).isSameAs(javaType);
149 | }
150 |
151 | @Test
152 | public void shouldRenameTypeThatMatch() throws Exception {
153 | // Given
154 | FullyQualifiedJavaType javaType = new FullyQualifiedJavaType(NEW_TYPE);
155 |
156 | // When
157 | FullyQualifiedJavaType renamed = allSet.renameType(javaType);
158 |
159 | // Then
160 | assertThat(renamed).isNotNull();
161 | assertThat(renamed.getFullyQualifiedName()).isEqualTo(ORIGINAL_TYPE);
162 | }
163 |
164 | @Test
165 | public void shouldNotRenameAttributesThatDontMatch() throws Exception {
166 | // Given
167 | String type = "some.other.Type";
168 | Attribute attribute = new Attribute("name", type);
169 |
170 | // When
171 | Attribute renamed = allSet.renameAttribute(attribute);
172 |
173 | // Then
174 | assertThat(renamed).isSameAs(attribute);
175 | }
176 |
177 | @Test
178 | public void shouldRenameAttributeThatMatch() throws Exception {
179 | // Given
180 | Attribute attribute = new Attribute("name", NEW_TYPE);
181 |
182 | // When
183 | Attribute renamed = allSet.renameAttribute(attribute);
184 |
185 | // Then
186 | assertThat(renamed).isNotNull();
187 | assertThat(renamed.getValue()).isEqualTo(ORIGINAL_TYPE);
188 | }
189 |
190 | @Test
191 | public void shouldNotRenameNullAnnotations() throws Exception {
192 | // Given
193 | List annotations = null;
194 |
195 | // When
196 | allSet.renameAnnotations(annotations);
197 |
198 | // Then
199 | }
200 |
201 | @Test
202 | public void shouldNotRenameAnnotationsThatDontMatch() throws Exception {
203 | // Given
204 | String type = "some.other.Type";
205 | List annotations = new ArrayList<>();
206 | annotations.add("@MultiLine({");
207 | annotations.add("\" line1\",");
208 | annotations.add("\" line2 " + type + "\",");
209 | annotations.add("\" line3\",");
210 | annotations.add("})");
211 | annotations.add("@SingleLine(\"" + type + "\")");
212 | final int annotationsSize = annotations.size();
213 |
214 | // When
215 | allSet.renameAnnotations(annotations);
216 |
217 | // Then
218 | assertThat(annotations).hasSize(annotationsSize);
219 | for (String annotation : annotations) {
220 | assertThat(annotation).doesNotContain(ORIGINAL_TYPE);
221 | }
222 | assertThat(annotations.get(2)).contains(type);
223 | assertThat(annotations.get(5)).contains(type);
224 | }
225 |
226 | @Test
227 | public void shouldRenameAnnotationsThatMatch() throws Exception {
228 | // Given
229 | List annotations = new ArrayList<>();
230 | annotations.add("@MultiLine({");
231 | annotations.add("\" line1\",");
232 | annotations.add("\" line2 " + NEW_TYPE + "\",");
233 | annotations.add("\" line3\",");
234 | annotations.add("})");
235 | annotations.add("@SingleLine(\"" + NEW_TYPE + "\")");
236 | final int annotationsSize = annotations.size();
237 |
238 | // When
239 | allSet.renameAnnotations(annotations);
240 |
241 | // Then
242 | assertThat(annotations).hasSize(annotationsSize);
243 | for (String annotation : annotations) {
244 | assertThat(annotation).doesNotContain(NEW_TYPE);
245 | }
246 | assertThat(annotations.get(2)).contains(ORIGINAL_TYPE);
247 | assertThat(annotations.get(5)).contains(ORIGINAL_TYPE);
248 | }
249 | }
250 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dcendents/mybatis/generator/plugin/wrap/WrapObjectPlugin.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.wrap;
2 |
3 | import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
4 |
5 | import java.util.HashMap;
6 | import java.util.HashSet;
7 | import java.util.List;
8 | import java.util.Map;
9 | import java.util.Set;
10 |
11 | import lombok.AccessLevel;
12 | import lombok.Getter;
13 | import lombok.NoArgsConstructor;
14 |
15 | import org.apache.commons.lang3.StringUtils;
16 | import org.mybatis.generator.api.IntrospectedColumn;
17 | import org.mybatis.generator.api.IntrospectedTable;
18 | import org.mybatis.generator.api.PluginAdapter;
19 | import org.mybatis.generator.api.dom.java.Field;
20 | import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
21 | import org.mybatis.generator.api.dom.java.JavaVisibility;
22 | import org.mybatis.generator.api.dom.java.Method;
23 | import org.mybatis.generator.api.dom.java.TopLevelClass;
24 |
25 | @NoArgsConstructor
26 | public class WrapObjectPlugin extends PluginAdapter {
27 | public static final String TABLE_NAME = "fullyQualifiedTableName";
28 | public static final String OBJECT_CLASS = "objectClass";
29 | public static final String OBJECT_FIELD_NAME = "objectFieldName";
30 | public static final String INCLUDES = "includes";
31 | public static final String EXCLUDES = "excludes";
32 |
33 | private String tableName;
34 | private Class> objectClass;
35 |
36 | @Getter(AccessLevel.PACKAGE)
37 | private Set includes = new HashSet<>();
38 | @Getter(AccessLevel.PACKAGE)
39 | private Set excludes = new HashSet<>();
40 |
41 | @Getter(AccessLevel.PACKAGE)
42 | private String objectFieldName;
43 |
44 | @Getter(AccessLevel.PACKAGE)
45 | private Set gettersToWrap = new HashSet<>();
46 | @Getter(AccessLevel.PACKAGE)
47 | private Set settersToWrap = new HashSet<>();
48 |
49 | @Getter(AccessLevel.PACKAGE)
50 | private Map wrappedGetters = new HashMap<>();
51 |
52 | @Override
53 | public boolean validate(List warnings) {
54 | tableName = properties.getProperty(TABLE_NAME);
55 | String objectClassName = properties.getProperty(OBJECT_CLASS);
56 |
57 | String warning = "Property %s not set for plugin %s";
58 | if (!stringHasValue(tableName)) {
59 | warnings.add(String.format(warning, TABLE_NAME, this.getClass().getSimpleName()));
60 | }
61 | if (!stringHasValue(objectClassName)) {
62 | warnings.add(String.format(warning, OBJECT_CLASS, this.getClass().getSimpleName()));
63 | } else {
64 | try {
65 | objectClass = Class.forName(objectClassName);
66 | } catch (ClassNotFoundException ex) {
67 | warnings.add(String.format("Could not load class %s in plugin %s", objectClassName, this.getClass()
68 | .getSimpleName()));
69 | }
70 | }
71 |
72 | String includesString = properties.getProperty(INCLUDES);
73 | if (stringHasValue(includesString)) {
74 | for (String include : includesString.split(",")) {
75 | includes.add(include.trim());
76 | }
77 | }
78 |
79 | String excludesString = properties.getProperty(EXCLUDES);
80 | if (stringHasValue(excludesString)) {
81 | for (String exclude : excludesString.split(",")) {
82 | excludes.add(exclude.trim());
83 | }
84 | }
85 |
86 | objectFieldName = properties.getProperty(OBJECT_FIELD_NAME);
87 | if (!stringHasValue(objectFieldName) && objectClass != null) {
88 | objectFieldName = StringUtils.uncapitalize(objectClass.getSimpleName());
89 | }
90 |
91 | return stringHasValue(tableName) && objectClass != null;
92 | }
93 |
94 | private boolean tableMatches(IntrospectedTable introspectedTable) {
95 | return tableName.equals(introspectedTable.getFullyQualifiedTableNameAtRuntime());
96 | }
97 |
98 | @Override
99 | public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
100 | if (tableMatches(introspectedTable)) {
101 | FullyQualifiedJavaType type = new FullyQualifiedJavaType(objectClass.getName());
102 | Field field = new Field(objectFieldName, type);
103 | field.setVisibility(JavaVisibility.PROTECTED);
104 | field.setInitializationString(String.format("new %s()", objectClass.getSimpleName()));
105 |
106 | field.addJavaDocLine("/**");
107 | field.addJavaDocLine(" * This field was generated by MyBatis Generator.");
108 | field.addJavaDocLine(" * This field corresponds to the wrapped object.");
109 | field.addJavaDocLine(" *");
110 | field.addJavaDocLine(" * @mbggenerated");
111 | field.addJavaDocLine(" */");
112 |
113 | topLevelClass.addField(field);
114 | topLevelClass.addImportedType(type);
115 | }
116 |
117 | return true;
118 | }
119 |
120 | @Override
121 | public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
122 | IntrospectedTable introspectedTable, ModelClassType modelClassType) {
123 | if (tableMatches(introspectedTable) && wrapField(field)) {
124 | topLevelClass.addImportedType(field.getType());
125 | return false;
126 | }
127 |
128 | return true;
129 | }
130 |
131 | private boolean wrapField(Field field) {
132 | if (includes.contains(field.getName()) || (includes.isEmpty() && !excludes.contains(field.getName()))) {
133 | return objectClassHasFieldGetter(field);
134 | }
135 |
136 | return false;
137 | }
138 |
139 | private boolean objectClassHasFieldGetter(Field field) {
140 | FullyQualifiedJavaType type = field.getType();
141 | String prefix = type.isPrimitive() && type.getShortName().equals("boolean") ? "is" : "get";
142 |
143 | String capitalized = StringUtils.capitalize(field.getName());
144 | String getterName = prefix + capitalized;
145 | String setterName = "set" + capitalized;
146 | String wrappedGetter = getterName;
147 |
148 | if (hasGetter(getterName)) {
149 | gettersToWrap.add(getterName);
150 | settersToWrap.add(setterName);
151 | wrappedGetters.put(getterName, wrappedGetter);
152 | return true;
153 | }
154 |
155 | // Check for possibility of boolean mismatch field (Boolean/boolean)
156 | if (type.isPrimitive() && type.getShortName().equals("boolean") && hasGetter("get" + capitalized)) {
157 | gettersToWrap.add(getterName);
158 | settersToWrap.add(setterName);
159 | wrappedGetters.put(getterName, "get" + capitalized);
160 | return true;
161 | } else if (!type.isPrimitive() && type.getFullyQualifiedName().equals("java.lang.Boolean") && hasGetter("is" + capitalized)) {
162 | gettersToWrap.add(getterName);
163 | settersToWrap.add(setterName);
164 | wrappedGetters.put(getterName, "is" + capitalized);
165 | return true;
166 | }
167 |
168 | return false;
169 | }
170 |
171 | private boolean hasGetter(String getterName) {
172 | try {
173 | objectClass.getMethod(getterName);
174 | return true;
175 | } catch (NoSuchMethodException ex) {
176 | return false;
177 | }
178 | }
179 |
180 | @Override
181 | public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass,
182 | IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
183 | if (tableMatches(introspectedTable) && gettersToWrap.contains(method.getName())) {
184 | method.getBodyLines().clear();
185 | method.addBodyLine(String.format("return this.%s.%s();", objectFieldName, wrappedGetters.get(method.getName())));
186 | }
187 |
188 | return true;
189 | }
190 |
191 | @Override
192 | public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass,
193 | IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
194 | if (tableMatches(introspectedTable) && settersToWrap.contains(method.getName())) {
195 | method.getBodyLines().clear();
196 | method.addBodyLine(String.format("this.%s.%s(%s);", objectFieldName, method.getName(), method
197 | .getParameters().get(0).getName()));
198 | }
199 |
200 | return true;
201 | }
202 |
203 | }
204 |
--------------------------------------------------------------------------------
/src/test/resources/log4j.dtd:
--------------------------------------------------------------------------------
1 |
2 |
18 |
19 |
20 |
21 |
22 |
23 |
26 |
27 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
50 |
51 |
52 |
53 |
54 |
55 |
59 |
60 |
62 |
63 |
66 |
67 |
68 |
69 |
70 |
71 |
74 |
78 |
79 |
80 |
83 |
84 |
85 |
88 |
89 |
90 |
91 |
92 |
93 |
96 |
97 |
98 |
99 |
100 |
103 |
104 |
105 |
109 |
110 |
111 |
112 |
113 |
117 |
118 |
119 |
120 |
124 |
125 |
126 |
127 |
128 |
129 |
134 |
135 |
136 |
137 |
138 |
143 |
144 |
145 |
146 |
148 |
149 |
150 |
152 |
153 |
154 |
157 |
158 |
159 |
160 |
164 |
165 |
166 |
169 |
170 |
171 |
174 |
175 |
176 |
180 |
181 |
182 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
203 |
204 |
205 |
206 |
208 |
209 |
210 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
230 |
231 |
232 |
233 |
234 |
238 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | com.github.dcendents
4 | mybatis-generator-plugins
5 | 1.4-SNAPSHOT
6 | MyBatis Generator Plugins
7 | Set of plugins for the mybatis-generator to further tweak the generated code.
8 | https://github.com/dcendents/mybatis-generator-plugins
9 | 2015
10 |
11 |
12 | Apache License, Version 2.0
13 | http://www.apache.org/licenses/LICENSE-2.0.html
14 |
15 |
16 |
17 | scm:git:https://github.com/dcendents/mybatis-generator-plugins.git
18 | https://github.com/dcendents/mybatis-generator-plugins
19 | HEAD
20 |
21 |
22 |
23 | dcendents
24 | Daniel Beland
25 | dcendents@gmail.com
26 |
27 |
28 |
29 | 1.7.25
30 |
31 |
32 |
33 |
34 |
35 | org.apache.maven.plugins
36 | maven-surefire-plugin
37 | 2.20.1
38 |
39 |
40 |
41 |
42 |
43 | org.apache.maven.plugins
44 | maven-compiler-plugin
45 | 3.7.0
46 |
47 | 1.8
48 | 1.8
49 |
50 |
51 |
52 | org.codehaus.mojo
53 | animal-sniffer-maven-plugin
54 | 1.16
55 |
56 |
57 | check
58 |
59 | check
60 |
61 |
62 |
63 | org.codehaus.mojo.signature
64 | java18
65 | 1.0
66 |
67 |
68 |
69 |
70 |
71 |
72 | org.jacoco
73 | jacoco-maven-plugin
74 | 0.8.0
75 |
76 |
77 | prepare-agent
78 |
79 | prepare-agent
80 |
81 |
82 |
83 | report
84 |
85 | report
86 |
87 |
88 |
89 |
90 |
91 | org.apache.maven.plugins
92 | maven-release-plugin
93 | 2.5.3
94 |
95 | v@{project.version}
96 | false
97 | deploy
98 | true
99 | true
100 | release
101 |
102 | pom.xml
103 |
104 |
105 |
106 |
107 | org.apache.maven.plugins
108 | maven-javadoc-plugin
109 | 3.0.0
110 |
111 |
112 | org.apache.maven.plugins
113 | maven-source-plugin
114 | 3.0.1
115 |
116 |
117 | org.apache.maven.plugins
118 | maven-deploy-plugin
119 | 2.8.2
120 |
121 |
122 |
123 |
124 |
125 | org.mybatis.generator
126 | mybatis-generator-core
127 | 1.3.6
128 | true
129 |
130 |
131 | org.projectlombok
132 | lombok
133 | 1.16.18
134 | provided
135 |
136 |
137 | org.slf4j
138 | slf4j-api
139 | ${slf4j.version}
140 |
141 |
142 | org.slf4j
143 | slf4j-log4j12
144 | ${slf4j.version}
145 | test
146 |
147 |
148 | org.apache.commons
149 | commons-lang3
150 | 3.7
151 |
152 |
153 | junit
154 | junit
155 | 4.12
156 | test
157 |
158 |
159 | org.mockito
160 | mockito-core
161 | 1.10.19
162 | test
163 |
164 |
165 | org.assertj
166 | assertj-core
167 | 2.9.0
168 | test
169 |
170 |
171 |
172 |
173 | bintray
174 | https://api.bintray.com/maven/dcendents/maven/com.github.dcendents:mybatis-generator-plugins
175 |
176 |
177 |
178 |
179 | release
180 |
181 |
182 |
183 | org.apache.maven.plugins
184 | maven-surefire-plugin
185 |
186 | true
187 |
188 |
189 |
190 | org.apache.maven.plugins
191 | maven-gpg-plugin
192 | 1.6
193 |
194 |
195 | sign-artifacts
196 | verify
197 |
198 | sign
199 |
200 |
201 |
202 |
203 | gpg2.exe
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 | m2e.version
213 |
214 |
215 |
216 |
217 |
218 |
220 |
221 | org.eclipse.m2e
222 | lifecycle-mapping
223 | 1.0.0
224 |
225 |
226 |
227 |
228 |
229 | org.jacoco
230 | jacoco-maven-plugin
231 | [0.7.4.201502262128,)
232 |
233 | prepare-agent
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
--------------------------------------------------------------------------------
/src/test/java/com/github/dcendents/mybatis/generator/plugin/locking/OptimisticLockingPluginTest.java:
--------------------------------------------------------------------------------
1 | package com.github.dcendents.mybatis.generator.plugin.locking;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 | import static org.assertj.core.api.BDDAssertions.then;
5 | import static org.mockito.BDDMockito.given;
6 | import static org.mockito.BDDMockito.willReturn;
7 | import static org.mockito.Matchers.any;
8 | import static org.mockito.Matchers.eq;
9 | import static org.mockito.Mockito.spy;
10 | import static org.mockito.Mockito.times;
11 | import static org.mockito.Mockito.verify;
12 |
13 | import java.util.ArrayList;
14 | import java.util.Arrays;
15 | import java.util.List;
16 |
17 | import org.junit.Before;
18 | import org.junit.Test;
19 | import org.junit.runner.RunWith;
20 | import org.mockito.Mock;
21 | import org.mockito.runners.MockitoJUnitRunner;
22 | import org.mybatis.generator.api.IntrospectedColumn;
23 | import org.mybatis.generator.api.IntrospectedTable;
24 | import org.mybatis.generator.api.dom.java.Interface;
25 | import org.mybatis.generator.api.dom.java.Method;
26 | import org.mybatis.generator.api.dom.java.TopLevelClass;
27 | import org.mybatis.generator.api.dom.xml.XmlElement;
28 |
29 | /**
30 | * Tests for the class OptimisticLockingPlugin.
31 | */
32 | @RunWith(MockitoJUnitRunner.class)
33 | public class OptimisticLockingPluginTest {
34 |
35 | private OptimisticLockingPlugin plugin;
36 |
37 | @Mock
38 | private XmlElement element;
39 | @Mock
40 | private Method method;
41 | @Mock
42 | private Method withLock;
43 | @Mock
44 | private IntrospectedTable introspectedTable;
45 | @Mock
46 | private TopLevelClass topLevelClass;
47 | @Mock
48 | private Interface interfaze;
49 |
50 | @Mock
51 | private IntrospectedColumn id;
52 | @Mock
53 | private IntrospectedColumn other;
54 | @Mock
55 | private IntrospectedColumn modificationDate;
56 |
57 |
58 | private static final String TABLE_NAME = "table_name";
59 | private static final String LOCK_COLUMN = "modification_date";
60 | private static final String LOCK_COLUMN_FUNCTION = "date_trunc('milliseconds', modification_date)";
61 |
62 | @Before
63 | public void init() throws Exception {
64 | given(id.getActualColumnName()).willReturn("id");
65 | given(other.getActualColumnName()).willReturn("other_column");
66 | given(modificationDate.getActualColumnName()).willReturn("modification_date");
67 |
68 | given(introspectedTable.getFullyQualifiedTableNameAtRuntime()).willReturn(TABLE_NAME);
69 | given(introspectedTable.getAllColumns()).willReturn(Arrays.asList(id, other, modificationDate));
70 |
71 | given(method.getName()).willReturn("methodName");
72 |
73 | plugin = new OptimisticLockingPlugin();
74 | plugin.getProperties().put(OptimisticLockingPlugin.TABLE_NAME, TABLE_NAME);
75 | plugin.getProperties().put(OptimisticLockingPlugin.LOCK_COLUMN, LOCK_COLUMN);
76 | plugin.getProperties().put(OptimisticLockingPlugin.LOCK_COLUMN_FUNCTION, LOCK_COLUMN_FUNCTION);
77 | plugin.validate(new ArrayList());
78 | }
79 |
80 | @Test
81 | public void shouldBeInvalidWithoutAnyPropertyConfigured() {
82 | // Given
83 | OptimisticLockingPlugin instance = new OptimisticLockingPlugin();
84 |
85 | // When
86 | List warnings = new ArrayList<>();
87 | boolean ok = instance.validate(warnings);
88 |
89 | // Then
90 | assertThat(ok).isFalse();
91 | assertThat(warnings).hasSize(2);
92 | }
93 |
94 | @Test
95 | public void shouldBeInvalidWithOnlyTheTableNameConfigured() {
96 | // Given
97 | OptimisticLockingPlugin instance = new OptimisticLockingPlugin();
98 | instance.getProperties().put(OptimisticLockingPlugin.TABLE_NAME, TABLE_NAME);
99 |
100 | // When
101 | List warnings = new ArrayList<>();
102 | boolean ok = instance.validate(warnings);
103 |
104 | // Then
105 | assertThat(ok).isFalse();
106 | assertThat(warnings).hasSize(1);
107 | }
108 |
109 | @Test
110 | public void shouldBeInvalidWithOnlyTheLockColumnConfigured() {
111 | // Given
112 | OptimisticLockingPlugin instance = new OptimisticLockingPlugin();
113 | instance.getProperties().put(OptimisticLockingPlugin.LOCK_COLUMN, LOCK_COLUMN);
114 |
115 | // When
116 | List warnings = new ArrayList<>();
117 | boolean ok = instance.validate(warnings);
118 |
119 | // Then
120 | assertThat(ok).isFalse();
121 | assertThat(warnings).hasSize(1);
122 | }
123 |
124 | @Test
125 | public void shouldBeValidWhenBothPropertiesAreConfigured() {
126 | // Given
127 | OptimisticLockingPlugin instance = new OptimisticLockingPlugin();
128 | instance.getProperties().put(OptimisticLockingPlugin.TABLE_NAME, TABLE_NAME);
129 | instance.getProperties().put(OptimisticLockingPlugin.LOCK_COLUMN, LOCK_COLUMN);
130 |
131 | // When
132 | List warnings = new ArrayList<>();
133 | boolean ok = instance.validate(warnings);
134 |
135 | // Then
136 | assertThat(ok).isTrue();
137 | assertThat(warnings).isEmpty();
138 | }
139 |
140 | @Test
141 | public void shouldSupportRegex() {
142 | // Given
143 | OptimisticLockingPlugin instance = new OptimisticLockingPlugin();
144 | instance.getProperties().put(OptimisticLockingPlugin.TABLE_NAME, "tab.*_n\\S+");
145 | instance.getProperties().put(OptimisticLockingPlugin.LOCK_COLUMN, LOCK_COLUMN);
146 | instance.validate(new ArrayList());
147 |
148 | // When
149 | boolean ok = instance.tableMatches(introspectedTable);
150 |
151 | // Then
152 | assertThat(ok).isTrue();
153 | }
154 |
155 | @Test
156 | public void shouldNotAddMethodIfTableDoesNotMatch() {
157 | // Given
158 | given(introspectedTable.getFullyQualifiedTableNameAtRuntime()).willReturn("wrong_name");
159 |
160 | // When
161 | boolean ok1 = plugin.clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(method, interfaze, introspectedTable);
162 | boolean ok2 = plugin.clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(method, topLevelClass, introspectedTable);
163 |
164 | // Then
165 | then(ok1).isTrue();
166 | then(ok2).isTrue();
167 | verify(interfaze, times(0)).addMethod(any(Method.class));
168 | verify(topLevelClass, times(0)).addMethod(any(Method.class));
169 | }
170 |
171 | @Test
172 | public void shouldAddNewMethod() {
173 | // Given
174 | OptimisticLockingPlugin plugin = spy(this.plugin);
175 | willReturn(withLock).given(plugin).addMethod(eq(method), eq(introspectedTable));
176 |
177 | // When
178 | boolean ok1 = plugin.clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(method, interfaze, introspectedTable);
179 | boolean ok2 = plugin.clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(method, topLevelClass, introspectedTable);
180 |
181 | // Then
182 | then(ok1).isTrue();
183 | then(ok2).isTrue();
184 | verify(plugin, times(2)).addMethod(eq(method), eq(introspectedTable));
185 | verify(interfaze).addMethod(eq(withLock));
186 | verify(topLevelClass).addMethod(eq(withLock));
187 | }
188 |
189 | @Test
190 | public void shouldCreateNewMethodUsingBaseName() {
191 | // Given
192 | Method realMethod = new Method("methodName");
193 |
194 | // When
195 | Method newMethod = plugin.addMethod(realMethod, introspectedTable);
196 |
197 | // Then
198 | then(newMethod).isNotNull();
199 | then(newMethod.getName()).isEqualTo(realMethod.getName() + OptimisticLockingPlugin.METHOD_SUFFIX);
200 | }
201 |
202 | @Test
203 | public void shouldAddConditionToWhereClauseInAnnotation() {
204 | // Given
205 | Method realMethod = new Method("methodName");
206 | realMethod.addAnnotation("@Update({");
207 | realMethod.addAnnotation(" \"update schema.table_name\",");
208 | realMethod.addAnnotation(" \"set id = #{id,jdbcType=INT},\",");
209 | realMethod.addAnnotation(" \"other_column = #{other,jdbcType=INT},\",");
210 | realMethod.addAnnotation(" \"where id = #{id,jdbcType=BIGINT}\"");
211 | realMethod.addAnnotation("})");
212 |
213 | // When
214 | Method newMethod = plugin.addMethod(realMethod, introspectedTable);
215 |
216 | // Then
217 | then(newMethod).isNotNull();
218 | then(newMethod.getName()).isEqualTo(realMethod.getName() + OptimisticLockingPlugin.METHOD_SUFFIX);
219 |
220 | then(newMethod.getAnnotations()).hasSize(realMethod.getAnnotations().size() + 1);
221 | then(newMethod.getAnnotations()).containsAll(realMethod.getAnnotations().subList(0, 4));
222 | then(newMethod.getAnnotations().get(4)).isEqualTo(realMethod.getAnnotations().get(4) + ",");
223 | then(newMethod.getAnnotations().get(5)).contains(String.format("and %s = ", LOCK_COLUMN_FUNCTION));
224 | then(newMethod.getAnnotations().get(6)).isEqualTo(realMethod.getAnnotations().get(5));
225 | }
226 |
227 | @Test
228 | public void shouldSetCorrectTypeHandler() {
229 | // Given
230 | String typeHandler = "some.type.Handler";
231 | given(modificationDate.getTypeHandler()).willReturn(typeHandler);
232 |
233 | Method realMethod = new Method("methodName");
234 | realMethod.addAnnotation("@Update({");
235 | realMethod.addAnnotation(" \"update schema.table_name\",");
236 | realMethod.addAnnotation(" \"set id = #{id,jdbcType=INT},\",");
237 | realMethod.addAnnotation(" \"other_column = #{other,jdbcType=INT},\",");
238 | realMethod.addAnnotation(" \"where id = #{id,jdbcType=BIGINT}\"");
239 | realMethod.addAnnotation("})");
240 |
241 | // When
242 | Method newMethod = plugin.addMethod(realMethod, introspectedTable);
243 |
244 | // Then
245 | then(newMethod.getAnnotations().get(5)).contains(typeHandler);
246 | }
247 |
248 | @Test
249 | public void shouldIgnoreMissingColumn() {
250 | // Given
251 | given(introspectedTable.getAllColumns()).willReturn(Arrays.asList(id, other));
252 |
253 | // When
254 | IntrospectedColumn column = plugin.getColumn(introspectedTable);
255 |
256 | // Then
257 | then(column).isNull();
258 | }
259 |
260 | }
261 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dcendents/mybatis/generator/plugin/dynamic/sql/DynamicSqlSupportClassGenerator.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2006-2018 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.dcendents.mybatis.generator.plugin.dynamic.sql;
17 |
18 | import static org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities.getEscapedColumnName;
19 | import static org.mybatis.generator.internal.util.StringUtility.escapeStringForJava;
20 |
21 | import java.util.List;
22 | import java.util.Map;
23 | import java.util.Properties;
24 |
25 | import org.apache.commons.lang3.StringUtils;
26 | import org.mybatis.generator.api.CommentGenerator;
27 | import org.mybatis.generator.api.IntrospectedColumn;
28 | import org.mybatis.generator.api.IntrospectedTable;
29 | import org.mybatis.generator.api.dom.java.Field;
30 | import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
31 | import org.mybatis.generator.api.dom.java.InnerClass;
32 | import org.mybatis.generator.api.dom.java.JavaVisibility;
33 | import org.mybatis.generator.api.dom.java.Method;
34 | import org.mybatis.generator.api.dom.java.TopLevelClass;
35 | import org.mybatis.generator.internal.util.JavaBeansUtil;
36 | import org.mybatis.generator.internal.util.StringUtility;
37 |
38 | public class DynamicSqlSupportClassGenerator {
39 | private IntrospectedTable introspectedTable;
40 | private CommentGenerator commentGenerator;
41 |
42 | private String sqlTableClassName;
43 | private boolean addAliasedColumns;
44 | private boolean addTableAlias;
45 | private String tableAliasFieldName;
46 | private Properties properties;
47 |
48 | private DynamicSqlSupportClassGenerator() {
49 | super();
50 | }
51 |
52 | public TopLevelClass generate() {
53 | TopLevelClass topLevelClass = buildBasicClass();
54 | Field tableField = calculateTableDefinition(topLevelClass);
55 | topLevelClass.addImportedType(tableField.getType());
56 | topLevelClass.addField(tableField);
57 |
58 | InnerClass innerClass = buildInnerTableClass(topLevelClass);
59 | topLevelClass.addInnerClass(innerClass);
60 |
61 | handleAliases(topLevelClass, innerClass, tableField.getName());
62 |
63 | List columns = introspectedTable.getAllColumns();
64 | for (IntrospectedColumn column : columns) {
65 | handleColumn(topLevelClass, innerClass, column, tableField.getName());
66 | }
67 |
68 | return topLevelClass;
69 | }
70 |
71 | private String calculateClassName() {
72 | FullyQualifiedJavaType mapperType = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaMapperType());
73 | FullyQualifiedJavaType recordType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
74 |
75 | return mapperType.getPackageName() + "." + recordType.getShortNameWithoutTypeArguments() + "DynamicSqlSupport"; //$NON-NLS-1$ //$NON-NLS-2$
76 |
77 | }
78 |
79 | private TopLevelClass buildBasicClass() {
80 | TopLevelClass topLevelClass = new TopLevelClass(calculateClassName());
81 | topLevelClass.setVisibility(JavaVisibility.PUBLIC);
82 | topLevelClass.setFinal(true);
83 | topLevelClass.addImportedType(new FullyQualifiedJavaType("org.mybatis.dynamic.sql.SqlColumn")); //$NON-NLS-1$
84 | topLevelClass.addImportedType(new FullyQualifiedJavaType("org.mybatis.dynamic.sql.SqlTable")); //$NON-NLS-1$
85 | topLevelClass.addImportedType(new FullyQualifiedJavaType("java.sql.JDBCType")); //$NON-NLS-1$
86 | return topLevelClass;
87 | }
88 |
89 | private InnerClass buildInnerTableClass(TopLevelClass topLevelClass) {
90 | FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(sqlTableClassName);
91 | InnerClass innerClass = new InnerClass(fqjt.getShortName());
92 | innerClass.setVisibility(JavaVisibility.PUBLIC);
93 | innerClass.setStatic(true);
94 | innerClass.setFinal(true);
95 | innerClass.setSuperClass(new FullyQualifiedJavaType("org.mybatis.dynamic.sql.SqlTable")); //$NON-NLS-1$
96 |
97 | Method method = new Method(fqjt.getShortName());
98 | method.setVisibility(JavaVisibility.PUBLIC);
99 | method.setConstructor(true);
100 | method.addBodyLine("super(\"" //$NON-NLS-1$
101 | + escapeStringForJava(introspectedTable.getFullyQualifiedTableNameAtRuntime()) + "\");"); //$NON-NLS-1$
102 | innerClass.addMethod(method);
103 |
104 | commentGenerator.addClassAnnotation(innerClass, introspectedTable, topLevelClass.getImportedTypes());
105 |
106 | return innerClass;
107 | }
108 |
109 | private Field calculateTableDefinition(TopLevelClass topLevelClass) {
110 | FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(sqlTableClassName);
111 | String fieldName = JavaBeansUtil.getValidPropertyName(sqlTableClassName);
112 | Field field = new Field(fieldName, fqjt);
113 | commentGenerator.addFieldAnnotation(field, introspectedTable, topLevelClass.getImportedTypes());
114 | field.setVisibility(JavaVisibility.PUBLIC);
115 | field.setStatic(true);
116 | field.setFinal(true);
117 |
118 | StringBuilder initializationString = new StringBuilder();
119 | initializationString.append(String.format("new %s()", //$NON-NLS-1$
120 | escapeStringForJava(sqlTableClassName)));
121 | field.setInitializationString(initializationString.toString());
122 | return field;
123 | }
124 |
125 | private void handleAliases(TopLevelClass topLevelClass, InnerClass innerClass, String tableFieldName) {
126 | // Standard MBG table alias
127 | String alias = introspectedTable.getFullyQualifiedTable().getAlias();
128 | if (addTableAlias && StringUtils.isNotBlank(alias) && StringUtils.isNotBlank(tableAliasFieldName)) {
129 | handleAlias(topLevelClass, innerClass, tableFieldName, tableAliasFieldName, alias);
130 | }
131 |
132 | // Extra aliases
133 | for (Map.Entry