View Javadoc
1   /*
2    *    Copyright 2006-2023 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.codegen.mybatis3.javamapper.elements.sqlprovider;
17  
18  import static org.mybatis.generator.internal.util.StringUtility.escapeStringForJava;
19  
20  import java.util.Set;
21  
22  import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
23  import org.mybatis.generator.api.dom.java.JavaVisibility;
24  import org.mybatis.generator.api.dom.java.Method;
25  import org.mybatis.generator.api.dom.java.Parameter;
26  import org.mybatis.generator.api.dom.java.TopLevelClass;
27  
28  public class ProviderCountByExampleMethodGenerator extends AbstractJavaProviderMethodGenerator {
29  
30      @Override
31      public void addClassElements(TopLevelClass topLevelClass) {
32          FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(introspectedTable.getExampleType());
33          Set<FullyQualifiedJavaType> importedTypes = initializeImportedTypes(fqjt);
34  
35          Method method = new Method(introspectedTable.getCountByExampleStatementId());
36          method.setVisibility(JavaVisibility.PUBLIC);
37          method.setReturnType(FullyQualifiedJavaType.getStringInstance());
38          method.addParameter(new Parameter(fqjt, "example")); //$NON-NLS-1$
39  
40          context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
41  
42          method.addBodyLine("SQL sql = new SQL();"); //$NON-NLS-1$
43          method.addBodyLine(String.format("sql.SELECT(\"count(*)\").FROM(\"%s\");", //$NON-NLS-1$
44                  escapeStringForJava(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())));
45          method.addBodyLine("applyWhere(sql, example, false);"); //$NON-NLS-1$
46          method.addBodyLine("return sql.toString();"); //$NON-NLS-1$
47  
48          if (context.getPlugins().providerCountByExampleMethodGenerated(method, topLevelClass, introspectedTable)) {
49              topLevelClass.addImportedTypes(importedTypes);
50              topLevelClass.addMethod(method);
51          }
52      }
53  }