View Javadoc
1   /*
2    *    Copyright 2009-2021 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 org.apache.ibatis.builder;
17  
18  import java.util.ArrayList;
19  import java.util.List;
20  import java.util.Map;
21  import java.util.StringTokenizer;
22  
23  import org.apache.ibatis.mapping.ParameterMapping;
24  import org.apache.ibatis.mapping.SqlSource;
25  import org.apache.ibatis.parsing.GenericTokenParser;
26  import org.apache.ibatis.parsing.TokenHandler;
27  import org.apache.ibatis.reflection.MetaClass;
28  import org.apache.ibatis.reflection.MetaObject;
29  import org.apache.ibatis.session.Configuration;
30  import org.apache.ibatis.type.JdbcType;
31  
32  /**
33   * @author Clinton Begin
34   */
35  public class SqlSourceBuilder extends BaseBuilder {
36  
37    private static final String PARAMETER_PROPERTIES = "javaType,jdbcType,mode,numericScale,resultMap,typeHandler,jdbcTypeName";
38  
39    public SqlSourceBuilder(Configuration configuration) {
40      super(configuration);
41    }
42  
43    public SqlSource parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {
44      ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType, additionalParameters);
45      GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
46      String sql;
47      if (configuration.isShrinkWhitespacesInSql()) {
48        sql = parser.parse(removeExtraWhitespaces(originalSql));
49      } else {
50        sql = parser.parse(originalSql);
51      }
52      return new StaticSqlSource(configuration, sql, handler.getParameterMappings());
53    }
54  
55    public static String removeExtraWhitespaces(String original) {
56      StringTokenizer tokenizer = new StringTokenizer(original);
57      StringBuilder builder = new StringBuilder();
58      boolean hasMoreTokens = tokenizer.hasMoreTokens();
59      while (hasMoreTokens) {
60        builder.append(tokenizer.nextToken());
61        hasMoreTokens = tokenizer.hasMoreTokens();
62        if (hasMoreTokens) {
63          builder.append(' ');
64        }
65      }
66      return builder.toString();
67    }
68  
69    private static class ParameterMappingTokenHandler extends BaseBuilder implements TokenHandler {
70  
71      private final List<ParameterMapping> parameterMappings = new ArrayList<>();
72      private final Class<?> parameterType;
73      private final MetaObject metaParameters;
74  
75      public ParameterMappingTokenHandler(Configuration configuration, Class<?> parameterType, Map<String, Object> additionalParameters) {
76        super(configuration);
77        this.parameterType = parameterType;
78        this.metaParameters = configuration.newMetaObject(additionalParameters);
79      }
80  
81      public List<ParameterMapping> getParameterMappings() {
82        return parameterMappings;
83      }
84  
85      @Override
86      public String handleToken(String content) {
87        parameterMappings.add(buildParameterMapping(content));
88        return "?";
89      }
90  
91      private ParameterMapping buildParameterMapping(String content) {
92        Map<String, String> propertiesMap = parseParameterMapping(content);
93        String property = propertiesMap.get("property");
94        Class<?> propertyType;
95        if (metaParameters.hasGetter(property)) { // issue #448 get type from additional params
96          propertyType = metaParameters.getGetterType(property);
97        } else if (typeHandlerRegistry.hasTypeHandler(parameterType)) {
98          propertyType = parameterType;
99        } else if (JdbcType.CURSOR.name().equals(propertiesMap.get("jdbcType"))) {
100         propertyType = java.sql.ResultSet.class;
101       } else if (property == null || Map.class.isAssignableFrom(parameterType)) {
102         propertyType = Object.class;
103       } else {
104         MetaClass metaClass = MetaClass.forClass(parameterType, configuration.getReflectorFactory());
105         if (metaClass.hasGetter(property)) {
106           propertyType = metaClass.getGetterType(property);
107         } else {
108           propertyType = Object.class;
109         }
110       }
111       ParameterMapping.Builder builder = new ParameterMapping.Builder(configuration, property, propertyType);
112       Class<?> javaType = propertyType;
113       String typeHandlerAlias = null;
114       for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {
115         String name = entry.getKey();
116         String value = entry.getValue();
117         if ("javaType".equals(name)) {
118           javaType = resolveClass(value);
119           builder.javaType(javaType);
120         } else if ("jdbcType".equals(name)) {
121           builder.jdbcType(resolveJdbcType(value));
122         } else if ("mode".equals(name)) {
123           builder.mode(resolveParameterMode(value));
124         } else if ("numericScale".equals(name)) {
125           builder.numericScale(Integer.valueOf(value));
126         } else if ("resultMap".equals(name)) {
127           builder.resultMapId(value);
128         } else if ("typeHandler".equals(name)) {
129           typeHandlerAlias = value;
130         } else if ("jdbcTypeName".equals(name)) {
131           builder.jdbcTypeName(value);
132         } else if ("property".equals(name)) {
133           // Do Nothing
134         } else if ("expression".equals(name)) {
135           throw new BuilderException("Expression based parameters are not supported yet");
136         } else {
137           throw new BuilderException("An invalid property '" + name + "' was found in mapping #{" + content + "}.  Valid properties are " + PARAMETER_PROPERTIES);
138         }
139       }
140       if (typeHandlerAlias != null) {
141         builder.typeHandler(resolveTypeHandler(javaType, typeHandlerAlias));
142       }
143       return builder.build();
144     }
145 
146     private Map<String, String> parseParameterMapping(String content) {
147       try {
148         return new ParameterExpression(content);
149       } catch (BuilderException ex) {
150         throw ex;
151       } catch (Exception ex) {
152         throw new BuilderException("Parsing error was found in mapping #{" + content + "}.  Check syntax #{property|(expression), var1=value1, var2=value2, ...} ", ex);
153       }
154     }
155   }
156 
157 }