View Javadoc
1   /*
2    *    Copyright 2006-2026 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    *       https://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 org.mybatis.generator.config;
17  
18  import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
19  import static org.mybatis.generator.internal.util.messages.Messages.getString;
20  
21  import java.util.List;
22  import java.util.Objects;
23  
24  import org.jspecify.annotations.Nullable;
25  import org.mybatis.generator.internal.db.DatabaseDialects;
26  
27  /**
28   * This class specifies that a key is auto-generated, either as an identity
29   * column (post insert), or as some other query like a sequence (pre insert).
30   *
31   * @author Jeff Butler
32   */
33  public class GeneratedKey {
34  
35      private final String column;
36      private final String runtimeSqlStatement;
37      private final boolean isIdentity;
38  
39      public GeneratedKey(@Nullable String column, @Nullable String configuredSqlStatement, boolean isIdentity) {
40          this.column = Objects.requireNonNull(column);
41          this.isIdentity = isIdentity;
42  
43          Objects.requireNonNull(configuredSqlStatement);
44          this.runtimeSqlStatement = DatabaseDialects.getDatabaseDialect(configuredSqlStatement)
45                  .map(DatabaseDialects::getIdentityRetrievalStatement)
46                  .orElse(configuredSqlStatement);
47      }
48  
49      public String getColumn() {
50          return column;
51      }
52  
53      public boolean isIdentity() {
54          return isIdentity;
55      }
56  
57      public String getRuntimeSqlStatement() {
58          return runtimeSqlStatement;
59      }
60  
61      public String getMyBatis3Order() {
62          return isIdentity ? "AFTER" : "BEFORE"; //$NON-NLS-1$ //$NON-NLS-2$
63      }
64  
65      public void validate(List<String> errors, String tableName, String contextId) {
66          if (!stringHasValue(runtimeSqlStatement)) {
67              errors.add(getString("ValidationError.7", tableName, contextId)); //$NON-NLS-1$
68          }
69      }
70  
71      public boolean isJdbcStandard() {
72          return "JDBC".equals(runtimeSqlStatement); //$NON-NLS-1$
73      }
74  }