1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.scripting.velocity;
17
18 import java.util.HashMap;
19 import java.util.Map;
20
21 import org.apache.ibatis.mapping.BoundSql;
22 import org.apache.ibatis.mapping.ParameterMapping;
23 import org.apache.ibatis.mapping.SqlSource;
24 import org.apache.ibatis.session.Configuration;
25
26 public class SQLScriptSource implements SqlSource {
27
28 protected static final String PARAMETER_OBJECT_KEY = "_parameter";
29 protected static final String DATABASE_ID_KEY = "_databaseId";
30 protected static final String MAPPING_COLLECTOR_KEY = "_pmc";
31 protected static final String VARIABLES_KEY = "_vars";
32
33 private static int templateIndex = 0;
34
35 private final ParameterMapping[] parameterMappingSources;
36 private final Object compiledScript;
37 private final Configuration configuration;
38
39 public SQLScriptSource(Configuration newConfiguration, String script, Class<?> parameterTypeClass) {
40 this.configuration = newConfiguration;
41 ParameterMappingSourceParser mappingParser = new ParameterMappingSourceParser(newConfiguration, script,
42 parameterTypeClass);
43 this.parameterMappingSources = mappingParser.getParameterMappingSources();
44 this.compiledScript = VelocityFacade.compile(mappingParser.getSql(), "velocity-template-" + (++templateIndex));
45 }
46
47 @Override
48 public BoundSql getBoundSql(Object parameterObject) {
49
50 final Map<String, Object> context = new HashMap<>();
51 final ParameterMappingCollector pmc = new ParameterMappingCollector(this.parameterMappingSources, context,
52 this.configuration);
53
54 context.put(DATABASE_ID_KEY, this.configuration.getDatabaseId());
55 context.put(PARAMETER_OBJECT_KEY, parameterObject);
56 context.put(MAPPING_COLLECTOR_KEY, pmc);
57 context.put(VARIABLES_KEY, this.configuration.getVariables());
58
59 final String sql = VelocityFacade.apply(this.compiledScript, context);
60 BoundSql boundSql = new BoundSql(this.configuration, sql, pmc.getParameterMappings(), parameterObject);
61 for (Map.Entry<String, Object> entry : context.entrySet()) {
62 boundSql.setAdditionalParameter(entry.getKey(), entry.getValue());
63 }
64
65 return boundSql;
66
67 }
68
69 }