1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.scripting.freemarker;
17
18 import java.io.IOException;
19 import java.util.List;
20 import java.util.Map;
21
22 import freemarker.core.Environment;
23 import freemarker.ext.util.WrapperTemplateModel;
24 import freemarker.template.DefaultListAdapter;
25 import freemarker.template.SimpleScalar;
26 import freemarker.template.TemplateBooleanModel;
27 import freemarker.template.TemplateDateModel;
28 import freemarker.template.TemplateDirectiveBody;
29 import freemarker.template.TemplateDirectiveModel;
30 import freemarker.template.TemplateException;
31 import freemarker.template.TemplateModel;
32 import freemarker.template.TemplateNumberModel;
33 import freemarker.template.TemplateScalarModel;
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77 public class MyBatisParamDirective implements TemplateDirectiveModel {
78 public static String DEFAULT_KEY = "p";
79 public static String DATABASE_ID_KEY = "_databaseId";
80
81 @Override
82 public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
83 throws TemplateException, IOException {
84 SimpleScalar name = (SimpleScalar) params.get("name");
85 if (params.containsKey("value")) {
86 Object valueObject = params.get("value");
87 Object value;
88 if (valueObject == null) {
89 value = null;
90 } else if (valueObject instanceof WrapperTemplateModel) {
91 value = ((WrapperTemplateModel) valueObject).getWrappedObject();
92 } else if (valueObject instanceof TemplateScalarModel) {
93 value = ((TemplateScalarModel) valueObject).getAsString();
94 } else if (valueObject instanceof TemplateNumberModel) {
95 value = ((TemplateNumberModel) valueObject).getAsNumber();
96 } else if (valueObject instanceof TemplateDateModel) {
97 value = ((TemplateDateModel) valueObject).getAsDate();
98 } else if (valueObject instanceof TemplateBooleanModel) {
99 value = ((TemplateBooleanModel) valueObject).getAsBoolean();
100 } else {
101 throw new UnsupportedOperationException(
102 String.format("Type %s is not supported yet in this context.", valueObject.getClass().getSimpleName()));
103 }
104
105 TemplateModel generatedParamsObject = env.getGlobalVariables().get(FreeMarkerSqlSource.GENERATED_PARAMS_KEY);
106 List generatedParams;
107 if (generatedParamsObject instanceof DefaultListAdapter) {
108 generatedParams = (List) ((DefaultListAdapter) generatedParamsObject).getWrappedObject();
109 } else {
110 generatedParams = ((GeneratedParamsTemplateModel) generatedParamsObject).getGeneratedParams();
111 }
112 String generatedParamName = "_p" + generatedParams.size();
113 env.getOut().write(String.format("#{%s}", generatedParamName));
114 generatedParams.add(value);
115 } else {
116 env.getOut().write(String.format("#{%s}", name));
117 }
118 }
119 }