• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mybatis / freemarker-scripting / #307

24 Sep 2023 01:19AM CUT coverage: 93.561%. Remained the same
#307

Pull #162

github

web-flow
Update dependency org.mybatis:mybatis-parent to v39
Pull Request #162: Update dependency org.mybatis:mybatis-parent to v39

247 of 264 relevant lines covered (93.56%)

0.94 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.12
/src/main/java/org/mybatis/scripting/freemarker/FreeMarkerSqlSource.java
1
/*
2
 *    Copyright 2015-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.scripting.freemarker;
17

18
import java.io.CharArrayWriter;
19
import java.io.IOException;
20
import java.util.ArrayList;
21
import java.util.HashMap;
22
import java.util.Map;
23

24
import org.apache.ibatis.builder.SqlSourceBuilder;
25
import org.apache.ibatis.mapping.BoundSql;
26
import org.apache.ibatis.mapping.SqlSource;
27
import org.apache.ibatis.session.Configuration;
28

29
import freemarker.template.SimpleScalar;
30
import freemarker.template.Template;
31
import freemarker.template.TemplateException;
32
import freemarker.template.Version;
33

34
/**
35
 * Applies provided parameter(s) to FreeMarker template. Then passes the result into default MyBatis engine (and it
36
 * finally replaces #{}-params to '?'-params). So, FreeMarker is used as preprocessor for MyBatis engine.
37
 *
38
 * @author elwood
39
 */
40
public class FreeMarkerSqlSource implements SqlSource {
41
  private final Template template;
42
  private final Configuration configuration;
43
  private final Version incompatibleImprovementsVersion;
44
  private final String databaseId;
45

46
  public static final String GENERATED_PARAMS_KEY = "__GENERATED__";
47

48
  public FreeMarkerSqlSource(Template template, Configuration configuration, Version incompatibleImprovementsVersion) {
1✔
49
    this.template = template;
1✔
50
    this.configuration = configuration;
1✔
51
    this.incompatibleImprovementsVersion = incompatibleImprovementsVersion;
1✔
52
    this.databaseId = configuration.getDatabaseId();
1✔
53
  }
1✔
54

55
  /**
56
   * Populates additional parameters to data context. Data context can be {@link java.util.Map} or
57
   * {@link org.mybatis.scripting.freemarker.ParamObjectAdapter} instance.
58
   */
59
  protected Object preProcessDataContext(Object dataContext, boolean isMap) {
60
    if (isMap) {
1✔
61
      ((Map<String, Object>) dataContext).put(MyBatisParamDirective.DEFAULT_KEY, new MyBatisParamDirective());
1✔
62
      ((Map<String, Object>) dataContext).put(MyBatisParamDirective.DATABASE_ID_KEY, new SimpleScalar(this.databaseId));
1✔
63
    } else {
64
      ((ParamObjectAdapter) dataContext).putAdditionalParam(MyBatisParamDirective.DEFAULT_KEY,
1✔
65
          new MyBatisParamDirective());
66
      ((ParamObjectAdapter) dataContext).putAdditionalParam(MyBatisParamDirective.DATABASE_ID_KEY,
1✔
67
          new SimpleScalar(this.databaseId));
68
    }
69
    return dataContext;
1✔
70
  }
71

72
  @Override
73
  public BoundSql getBoundSql(Object parameterObject) {
74
    // Add to passed parameterObject our predefined directive - MyBatisParamDirective
75
    // It will be available as "p" inside templates
76
    Object dataContext;
77
    ArrayList generatedParams = new ArrayList<>();
1✔
78
    if (parameterObject != null) {
1✔
79
      if (parameterObject instanceof Map) {
1✔
80
        HashMap<String, Object> map = new HashMap<>((Map<String, Object>) parameterObject);
1✔
81
        map.put(GENERATED_PARAMS_KEY, generatedParams);
1✔
82
        dataContext = preProcessDataContext(map, true);
1✔
83
      } else {
1✔
84
        ParamObjectAdapter adapter = new ParamObjectAdapter(parameterObject, generatedParams,
1✔
85
            incompatibleImprovementsVersion);
86
        dataContext = preProcessDataContext(adapter, false);
1✔
87
      }
1✔
88
    } else {
89
      HashMap<Object, Object> map = new HashMap<>();
1✔
90
      map.put(GENERATED_PARAMS_KEY, generatedParams);
1✔
91
      dataContext = preProcessDataContext(map, true);
1✔
92
    }
93

94
    CharArrayWriter writer = new CharArrayWriter();
1✔
95
    try {
96
      template.process(dataContext, writer);
1✔
97
    } catch (TemplateException | IOException e) {
×
98
      throw new RuntimeException(e);
×
99
    }
1✔
100

101
    // We got SQL ready for MyBatis here. This SQL contains
102
    // params declarations like "#{param}",
103
    // they will be replaced to '?' by MyBatis engine further
104
    String sql = writer.toString();
1✔
105

106
    if (!generatedParams.isEmpty()) {
1✔
107
      if (!(parameterObject instanceof Map)) {
1✔
108
        throw new UnsupportedOperationException("Auto-generated prepared statements parameters"
1✔
109
            + " are not available if using parameters object. Use @Param-annotated parameters" + " instead.");
110
      }
111

112
      Map<String, Object> parametersMap = (Map<String, Object>) parameterObject;
1✔
113
      for (int i = 0; i < generatedParams.size(); i++) {
1✔
114
        parametersMap.put("_p" + i, generatedParams.get(i));
1✔
115
      }
116
    }
117

118
    // Pass retrieved SQL into MyBatis engine, it will substitute prepared-statements parameters
119
    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
1✔
120
    Class<?> parameterType1 = parameterObject == null ? Object.class : parameterObject.getClass();
1✔
121
    SqlSource sqlSource = sqlSourceParser.parse(sql, parameterType1, new HashMap<String, Object>());
1✔
122
    return sqlSource.getBoundSql(parameterObject);
1✔
123
  }
124
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc