RawSqlSource.java

  1. /*
  2.  *    Copyright 2009-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.apache.ibatis.scripting.defaults;

  17. import java.util.HashMap;

  18. import org.apache.ibatis.builder.SqlSourceBuilder;
  19. import org.apache.ibatis.mapping.BoundSql;
  20. import org.apache.ibatis.mapping.SqlSource;
  21. import org.apache.ibatis.scripting.xmltags.DynamicContext;
  22. import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
  23. import org.apache.ibatis.scripting.xmltags.SqlNode;
  24. import org.apache.ibatis.session.Configuration;

  25. /**
  26.  * Static SqlSource. It is faster than {@link DynamicSqlSource} because mappings are calculated during startup.
  27.  *
  28.  * @since 3.2.0
  29.  *
  30.  * @author Eduardo Macarron
  31.  */
  32. public class RawSqlSource implements SqlSource {

  33.   private final SqlSource sqlSource;

  34.   public RawSqlSource(Configuration configuration, SqlNode rootSqlNode, Class<?> parameterType) {
  35.     this(configuration, getSql(configuration, rootSqlNode), parameterType);
  36.   }

  37.   public RawSqlSource(Configuration configuration, String sql, Class<?> parameterType) {
  38.     SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
  39.     Class<?> clazz = parameterType == null ? Object.class : parameterType;
  40.     sqlSource = sqlSourceParser.parse(sql, clazz, new HashMap<>());
  41.   }

  42.   private static String getSql(Configuration configuration, SqlNode rootSqlNode) {
  43.     DynamicContext context = new DynamicContext(configuration, null);
  44.     rootSqlNode.apply(context);
  45.     return context.getSql();
  46.   }

  47.   @Override
  48.   public BoundSql getBoundSql(Object parameterObject) {
  49.     return sqlSource.getBoundSql(parameterObject);
  50.   }

  51. }