1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.executor.keygen;
17
18 import java.lang.reflect.Type;
19 import java.sql.ResultSet;
20 import java.sql.ResultSetMetaData;
21 import java.sql.SQLException;
22 import java.sql.Statement;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Set;
32
33 import org.apache.ibatis.binding.MapperMethod.ParamMap;
34 import org.apache.ibatis.executor.Executor;
35 import org.apache.ibatis.executor.ExecutorException;
36 import org.apache.ibatis.mapping.MappedStatement;
37 import org.apache.ibatis.reflection.ArrayUtil;
38 import org.apache.ibatis.reflection.MetaObject;
39 import org.apache.ibatis.reflection.ParamNameResolver;
40 import org.apache.ibatis.session.Configuration;
41 import org.apache.ibatis.session.defaults.DefaultSqlSession.StrictMap;
42 import org.apache.ibatis.type.JdbcType;
43 import org.apache.ibatis.type.TypeHandler;
44 import org.apache.ibatis.type.TypeHandlerRegistry;
45
46
47
48
49
50 public class Jdbc3KeyGenerator implements KeyGenerator {
51
52 private static final String SECOND_GENERIC_PARAM_NAME = ParamNameResolver.GENERIC_NAME_PREFIX + "2";
53
54
55
56
57
58
59 public static final Jdbc3KeyGenerator INSTANCE = new Jdbc3KeyGenerator();
60
61 private static final String MSG_TOO_MANY_KEYS = "Too many keys are generated. There are only %d target objects. "
62 + "You either specified a wrong 'keyProperty' or encountered a driver bug like #1523.";
63
64 private static final String MSG_TOO_MANY_KEYS_FOR_MAP = "Too many keys are generated. There are only %d target object(s). "
65 + "A 'Map' passed as the sole parameter is treated as a single target object, so keys generated by a multi-row "
66 + "insert cannot be assigned to a collection nested in the 'Map'. Pass the collection itself as the sole parameter, "
67 + "or declare the parameters with @Param and prefix 'keyProperty' with the parameter name (e.g. 'list.id').";
68
69 @Override
70 public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
71
72 }
73
74 @Override
75 public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
76 processBatch(ms, stmt, parameter);
77 }
78
79 public void processBatch(MappedStatement ms, Statement stmt, Object parameter) {
80 final String[] keyProperties = ms.getKeyProperties();
81 if (keyProperties == null || keyProperties.length == 0) {
82 return;
83 }
84 try (ResultSet rs = stmt.getGeneratedKeys()) {
85 final ResultSetMetaData rsmd = rs.getMetaData();
86 final Configuration configuration = ms.getConfiguration();
87 if (rsmd.getColumnCount() < keyProperties.length) {
88
89 } else {
90 assignKeys(configuration, rs, rsmd, keyProperties, parameter);
91 }
92 } catch (Exception e) {
93 throw new ExecutorException("Error getting generated key or setting result to parameter object. Cause: " + e, e);
94 }
95 }
96
97 @SuppressWarnings("unchecked")
98 private void assignKeys(Configuration configuration, ResultSet rs, ResultSetMetaData rsmd, String[] keyProperties,
99 Object parameter) throws SQLException {
100 if (parameter instanceof ParamMap || parameter instanceof StrictMap) {
101
102 assignKeysToParamMap(configuration, rs, rsmd, keyProperties, (Map<String, ?>) parameter);
103 } else if (parameter instanceof ArrayList && !((ArrayList<?>) parameter).isEmpty()
104 && ((ArrayList<?>) parameter).get(0) instanceof ParamMap) {
105
106 assignKeysToParamMapList(configuration, rs, rsmd, keyProperties, (ArrayList<ParamMap<?>>) parameter);
107 } else {
108
109 assignKeysToParam(configuration, rs, rsmd, keyProperties, parameter);
110 }
111 }
112
113 private void assignKeysToParam(Configuration configuration, ResultSet rs, ResultSetMetaData rsmd,
114 String[] keyProperties, Object parameter) throws SQLException {
115 Collection<?> params = collectionize(parameter);
116 if (params.isEmpty()) {
117 return;
118 }
119 List<KeyAssigner> assignerList = new ArrayList<>();
120 for (int i = 0; i < keyProperties.length; i++) {
121 assignerList.add(new KeyAssigner(configuration, rsmd, i + 1, null, keyProperties[i]));
122 }
123 Iterator<?> iterator = params.iterator();
124 while (rs.next()) {
125 if (!iterator.hasNext()) {
126 throw new ExecutorException(
127 String.format(parameter instanceof Map ? MSG_TOO_MANY_KEYS_FOR_MAP : MSG_TOO_MANY_KEYS, params.size()));
128 }
129 Object param = iterator.next();
130 assignerList.forEach(x -> x.assign(rs, param));
131 }
132 }
133
134 private void assignKeysToParamMapList(Configuration configuration, ResultSet rs, ResultSetMetaData rsmd,
135 String[] keyProperties, ArrayList<ParamMap<?>> paramMapList) throws SQLException {
136 Iterator<ParamMap<?>> iterator = paramMapList.iterator();
137 List<KeyAssigner> assignerList = new ArrayList<>();
138 long counter = 0;
139 while (rs.next()) {
140 if (!iterator.hasNext()) {
141 throw new ExecutorException(String.format(MSG_TOO_MANY_KEYS, counter));
142 }
143 ParamMap<?> paramMap = iterator.next();
144 if (assignerList.isEmpty()) {
145 for (int i = 0; i < keyProperties.length; i++) {
146 assignerList
147 .add(getAssignerForParamMap(configuration, rsmd, i + 1, paramMap, keyProperties[i], keyProperties, false)
148 .getValue());
149 }
150 }
151 assignerList.forEach(x -> x.assign(rs, paramMap));
152 counter++;
153 }
154 }
155
156 private void assignKeysToParamMap(Configuration configuration, ResultSet rs, ResultSetMetaData rsmd,
157 String[] keyProperties, Map<String, ?> paramMap) throws SQLException {
158 if (paramMap.isEmpty()) {
159 return;
160 }
161 Map<String, Entry<Iterator<?>, List<KeyAssigner>>> assignerMap = new HashMap<>();
162 for (int i = 0; i < keyProperties.length; i++) {
163 Entry<String, KeyAssigner> entry = getAssignerForParamMap(configuration, rsmd, i + 1, paramMap, keyProperties[i],
164 keyProperties, true);
165 Entry<Iterator<?>, List<KeyAssigner>> iteratorPair = assignerMap.computeIfAbsent(entry.getKey(),
166 k -> Map.entry(collectionize(paramMap.get(k)).iterator(), new ArrayList<>()));
167 iteratorPair.getValue().add(entry.getValue());
168 }
169 long counter = 0;
170 while (rs.next()) {
171 for (Entry<Iterator<?>, List<KeyAssigner>> pair : assignerMap.values()) {
172 if (!pair.getKey().hasNext()) {
173 throw new ExecutorException(String.format(MSG_TOO_MANY_KEYS, counter));
174 }
175 Object param = pair.getKey().next();
176 pair.getValue().forEach(x -> x.assign(rs, param));
177 }
178 counter++;
179 }
180 }
181
182 private Entry<String, KeyAssigner> getAssignerForParamMap(Configuration config, ResultSetMetaData rsmd,
183 int columnPosition, Map<String, ?> paramMap, String keyProperty, String[] keyProperties, boolean omitParamName) {
184 Set<String> keySet = paramMap.keySet();
185
186
187 boolean singleParam = !keySet.contains(SECOND_GENERIC_PARAM_NAME);
188 int firstDot = keyProperty.indexOf('.');
189 if (firstDot == -1) {
190 if (singleParam) {
191 return getAssignerForSingleParam(config, rsmd, columnPosition, paramMap, keyProperty, omitParamName);
192 }
193 throw new ExecutorException("Could not determine which parameter to assign generated keys to. "
194 + "Note that when there are multiple parameters, 'keyProperty' must include the parameter name (e.g. 'param.id'). "
195 + "Specified key properties are " + ArrayUtil.toString(keyProperties) + " and available parameters are "
196 + keySet);
197 }
198 String paramName = keyProperty.substring(0, firstDot);
199 if (keySet.contains(paramName)) {
200 String argParamName = omitParamName ? null : paramName;
201 String argKeyProperty = keyProperty.substring(firstDot + 1);
202 return Map.entry(paramName, new KeyAssigner(config, rsmd, columnPosition, argParamName, argKeyProperty));
203 }
204 if (singleParam) {
205 return getAssignerForSingleParam(config, rsmd, columnPosition, paramMap, keyProperty, omitParamName);
206 } else {
207 throw new ExecutorException("Could not find parameter '" + paramName + "'. "
208 + "Note that when there are multiple parameters, 'keyProperty' must include the parameter name (e.g. 'param.id'). "
209 + "Specified key properties are " + ArrayUtil.toString(keyProperties) + " and available parameters are "
210 + keySet);
211 }
212 }
213
214 private Entry<String, KeyAssigner> getAssignerForSingleParam(Configuration config, ResultSetMetaData rsmd,
215 int columnPosition, Map<String, ?> paramMap, String keyProperty, boolean omitParamName) {
216
217 String singleParamName = nameOfSingleParam(paramMap);
218 String argParamName = omitParamName ? null : singleParamName;
219 return Map.entry(singleParamName, new KeyAssigner(config, rsmd, columnPosition, argParamName, keyProperty));
220 }
221
222 private static String nameOfSingleParam(Map<String, ?> paramMap) {
223
224 return paramMap.keySet().iterator().next();
225 }
226
227 private static Collection<?> collectionize(Object param) {
228 if (param instanceof Collection) {
229 return (Collection<?>) param;
230 }
231 if (param instanceof Object[]) {
232 return Arrays.asList((Object[]) param);
233 } else {
234 return Arrays.asList(param);
235 }
236 }
237
238 private static class KeyAssigner {
239 private final Configuration configuration;
240 private final ResultSetMetaData rsmd;
241 private final TypeHandlerRegistry typeHandlerRegistry;
242 private final int columnPosition;
243 private final String paramName;
244 private final String propertyName;
245 private TypeHandler<?> typeHandler;
246
247 protected KeyAssigner(Configuration configuration, ResultSetMetaData rsmd, int columnPosition, String paramName,
248 String propertyName) {
249 this.configuration = configuration;
250 this.rsmd = rsmd;
251 this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
252 this.columnPosition = columnPosition;
253 this.paramName = paramName;
254 this.propertyName = propertyName;
255 }
256
257 protected void assign(ResultSet rs, Object param) {
258 if (paramName != null) {
259
260 param = ((ParamMap<?>) param).get(paramName);
261 }
262 MetaObject metaParam = configuration.newMetaObject(param);
263 try {
264 if (typeHandler == null) {
265 if (!metaParam.hasSetter(propertyName)) {
266 throw new ExecutorException("No setter found for the keyProperty '" + propertyName + "' in '"
267 + metaParam.getOriginalObject().getClass().getName() + "'.");
268 }
269 Type propertyType = metaParam.getGenericSetterType(propertyName).getKey();
270 JdbcType jdbcType = JdbcType.forCode(rsmd.getColumnType(columnPosition));
271 typeHandler = typeHandlerRegistry.getTypeHandler(propertyType, jdbcType);
272 if (typeHandler == null) {
273 typeHandler = typeHandlerRegistry.getTypeHandler(jdbcType);
274 }
275 }
276 if (typeHandler == null) {
277
278 } else {
279 Object value = typeHandler.getResult(rs, columnPosition);
280 metaParam.setValue(propertyName, value);
281 }
282 } catch (SQLException e) {
283 throw new ExecutorException("Error getting generated key or setting result to parameter object. Cause: " + e,
284 e);
285 }
286 }
287 }
288 }