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

mybatis / mybatis-3 / 2686

01 Feb 2025 09:55PM UTC coverage: 87.093% (-0.1%) from 87.217%
2686

Pull #3379

github

web-flow
Merge c97c5c598 into 3d71c862a
Pull Request #3379: Resolve type handler based on `java.lang.reflect.Type` instead of `Class` and respect runtime JDBC type

3825 of 4663 branches covered (82.03%)

515 of 579 new or added lines in 36 files covered. (88.95%)

28 existing lines in 6 files now uncovered.

9912 of 11381 relevant lines covered (87.09%)

0.87 hits per line

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

89.0
/src/main/java/org/apache/ibatis/type/TypeHandlerRegistry.java
1
/*
2
 *    Copyright 2009-2025 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.type;
17

18
import java.io.InputStream;
19
import java.io.Reader;
20
import java.lang.reflect.Constructor;
21
import java.lang.reflect.Modifier;
22
import java.lang.reflect.ParameterizedType;
23
import java.lang.reflect.Type;
24
import java.math.BigDecimal;
25
import java.math.BigInteger;
26
import java.sql.Time;
27
import java.sql.Timestamp;
28
import java.time.Instant;
29
import java.time.LocalDate;
30
import java.time.LocalDateTime;
31
import java.time.LocalTime;
32
import java.time.Month;
33
import java.time.OffsetDateTime;
34
import java.time.OffsetTime;
35
import java.time.Year;
36
import java.time.YearMonth;
37
import java.time.ZonedDateTime;
38
import java.time.chrono.JapaneseDate;
39
import java.util.Collection;
40
import java.util.Collections;
41
import java.util.Date;
42
import java.util.EnumMap;
43
import java.util.HashMap;
44
import java.util.HashSet;
45
import java.util.Map;
46
import java.util.Map.Entry;
47
import java.util.Set;
48
import java.util.concurrent.ConcurrentHashMap;
49

50
import org.apache.ibatis.binding.MapperMethod.ParamMap;
51
import org.apache.ibatis.io.ResolverUtil;
52
import org.apache.ibatis.io.Resources;
53
import org.apache.ibatis.reflection.TypeParameterResolver;
54
import org.apache.ibatis.session.Configuration;
55

56
/**
57
 * @author Clinton Begin
58
 * @author Kazuki Shimizu
59
 */
60
public final class TypeHandlerRegistry {
61

62
  public static final ObjectTypeHandler OBJECT_TYPE_HANDLER = new ObjectTypeHandler();
1✔
63

64
  private final Map<JdbcType, TypeHandler<?>> jdbcTypeHandlerMap = new EnumMap<>(JdbcType.class);
1✔
65
  private final Map<Type, Map<JdbcType, TypeHandler<?>>> typeHandlerMap = new ConcurrentHashMap<>();
1✔
66
  private final Map<Type, Entry<Constructor<?>, Set<JdbcType>>> smartHandlers = new ConcurrentHashMap<>();
1✔
67
  @Deprecated
1✔
68
  private final Map<Class<?>, TypeHandler<?>> allTypeHandlersMap = new HashMap<>();
69

70
  private static final Map<JdbcType, TypeHandler<?>> NULL_TYPE_HANDLER_MAP = Collections.emptyMap();
1✔
71

72
  private Class<? extends TypeHandler> defaultEnumTypeHandler = EnumTypeHandler.class;
1✔
73

74
  /**
75
   * The default constructor.
76
   */
77
  public TypeHandlerRegistry() {
78
    this(new Configuration());
1✔
79
  }
1✔
80

81
  /**
82
   * The constructor that pass the MyBatis configuration.
83
   *
84
   * @param configuration
85
   *          a MyBatis configuration
86
   *
87
   * @since 3.5.4
88
   */
89
  public TypeHandlerRegistry(Configuration configuration) {
1✔
90
    register(Boolean.class, new BooleanTypeHandler());
1✔
91
    register(boolean.class, new BooleanTypeHandler());
1✔
92
    register(JdbcType.BOOLEAN, new BooleanTypeHandler());
1✔
93
    register(JdbcType.BIT, new BooleanTypeHandler());
1✔
94

95
    register(Byte.class, new ByteTypeHandler());
1✔
96
    register(byte.class, new ByteTypeHandler());
1✔
97
    register(JdbcType.TINYINT, new ByteTypeHandler());
1✔
98

99
    register(Short.class, new ShortTypeHandler());
1✔
100
    register(short.class, new ShortTypeHandler());
1✔
101
    register(JdbcType.SMALLINT, new ShortTypeHandler());
1✔
102

103
    register(Integer.class, new IntegerTypeHandler());
1✔
104
    register(int.class, new IntegerTypeHandler());
1✔
105
    register(JdbcType.INTEGER, new IntegerTypeHandler());
1✔
106

107
    register(Long.class, new LongTypeHandler());
1✔
108
    register(long.class, new LongTypeHandler());
1✔
109

110
    register(Float.class, new FloatTypeHandler());
1✔
111
    register(float.class, new FloatTypeHandler());
1✔
112
    register(JdbcType.FLOAT, new FloatTypeHandler());
1✔
113

114
    register(Double.class, new DoubleTypeHandler());
1✔
115
    register(double.class, new DoubleTypeHandler());
1✔
116
    register(JdbcType.DOUBLE, new DoubleTypeHandler());
1✔
117

118
    register(Reader.class, new ClobReaderTypeHandler());
1✔
119
    register(String.class, new StringTypeHandler());
1✔
120
    register(String.class, JdbcType.CHAR, new StringTypeHandler());
1✔
121
    register(String.class, JdbcType.CLOB, new ClobTypeHandler());
1✔
122
    register(String.class, JdbcType.VARCHAR, new StringTypeHandler());
1✔
123
    register(String.class, JdbcType.LONGVARCHAR, new StringTypeHandler());
1✔
124
    register(String.class, JdbcType.NVARCHAR, new NStringTypeHandler());
1✔
125
    register(String.class, JdbcType.NCHAR, new NStringTypeHandler());
1✔
126
    register(String.class, JdbcType.NCLOB, new NClobTypeHandler());
1✔
127
    register(JdbcType.CHAR, new StringTypeHandler());
1✔
128
    register(JdbcType.VARCHAR, new StringTypeHandler());
1✔
129
    register(JdbcType.CLOB, new ClobTypeHandler());
1✔
130
    register(JdbcType.LONGVARCHAR, new StringTypeHandler());
1✔
131
    register(JdbcType.NVARCHAR, new NStringTypeHandler());
1✔
132
    register(JdbcType.NCHAR, new NStringTypeHandler());
1✔
133
    register(JdbcType.NCLOB, new NClobTypeHandler());
1✔
134

135
    register(JdbcType.ARRAY, new ArrayTypeHandler());
1✔
136

137
    register(BigInteger.class, new BigIntegerTypeHandler());
1✔
138
    register(JdbcType.BIGINT, new LongTypeHandler());
1✔
139

140
    register(BigDecimal.class, new BigDecimalTypeHandler());
1✔
141
    register(JdbcType.REAL, new BigDecimalTypeHandler());
1✔
142
    register(JdbcType.DECIMAL, new BigDecimalTypeHandler());
1✔
143
    register(JdbcType.NUMERIC, new BigDecimalTypeHandler());
1✔
144

145
    register(InputStream.class, new BlobInputStreamTypeHandler());
1✔
146
    register(Byte[].class, new ByteObjectArrayTypeHandler());
1✔
147
    register(Byte[].class, JdbcType.BLOB, new BlobByteObjectArrayTypeHandler());
1✔
148
    register(Byte[].class, JdbcType.LONGVARBINARY, new BlobByteObjectArrayTypeHandler());
1✔
149
    register(byte[].class, new ByteArrayTypeHandler());
1✔
150
    register(byte[].class, JdbcType.BLOB, new BlobTypeHandler());
1✔
151
    register(byte[].class, JdbcType.LONGVARBINARY, new BlobTypeHandler());
1✔
152
    register(JdbcType.LONGVARBINARY, new BlobTypeHandler());
1✔
153
    register(JdbcType.BLOB, new BlobTypeHandler());
1✔
154

155
    register(Date.class, new DateTypeHandler());
1✔
156
    register(Date.class, JdbcType.DATE, new DateOnlyTypeHandler());
1✔
157
    register(Date.class, JdbcType.TIME, new TimeOnlyTypeHandler());
1✔
158
    register(JdbcType.TIMESTAMP, new DateTypeHandler());
1✔
159
    register(JdbcType.DATE, new DateOnlyTypeHandler());
1✔
160
    register(JdbcType.TIME, new TimeOnlyTypeHandler());
1✔
161

162
    register(java.sql.Date.class, new SqlDateTypeHandler());
1✔
163
    register(Time.class, new SqlTimeTypeHandler());
1✔
164
    register(Timestamp.class, new SqlTimestampTypeHandler());
1✔
165

166
    register(String.class, JdbcType.SQLXML, new SqlxmlTypeHandler());
1✔
167

168
    register(Instant.class, new InstantTypeHandler());
1✔
169
    register(LocalDateTime.class, new LocalDateTimeTypeHandler());
1✔
170
    register(LocalDate.class, new LocalDateTypeHandler());
1✔
171
    register(LocalTime.class, new LocalTimeTypeHandler());
1✔
172
    register(OffsetDateTime.class, new OffsetDateTimeTypeHandler());
1✔
173
    register(OffsetTime.class, new OffsetTimeTypeHandler());
1✔
174
    register(ZonedDateTime.class, new ZonedDateTimeTypeHandler());
1✔
175
    register(Month.class, new MonthTypeHandler());
1✔
176
    register(Year.class, new YearTypeHandler());
1✔
177
    register(YearMonth.class, new YearMonthTypeHandler());
1✔
178
    register(JapaneseDate.class, new JapaneseDateTypeHandler());
1✔
179

180
    // issue #273
181
    register(Character.class, new CharacterTypeHandler());
1✔
182
    register(char.class, new CharacterTypeHandler());
1✔
183
  }
1✔
184

185
  /**
186
   * Set a default {@link TypeHandler} class for {@link Enum}. A default {@link TypeHandler} is
187
   * {@link org.apache.ibatis.type.EnumTypeHandler}.
188
   *
189
   * @param typeHandler
190
   *          a type handler class for {@link Enum}
191
   *
192
   * @since 3.4.5
193
   */
194
  public void setDefaultEnumTypeHandler(Class<? extends TypeHandler> typeHandler) {
195
    this.defaultEnumTypeHandler = typeHandler;
×
196
  }
×
197

198
  public boolean hasTypeHandler(Class<?> javaType) {
199
    return hasTypeHandler(javaType, null);
1✔
200
  }
201

202
  @Deprecated
203
  public boolean hasTypeHandler(TypeReference<?> javaTypeReference) {
204
    return hasTypeHandler(javaTypeReference, null);
×
205
  }
206

207
  public boolean hasTypeHandler(Type javaType, JdbcType jdbcType) {
208
    return javaType != null && getTypeHandler(javaType, jdbcType) != null;
1!
209
  }
210

211
  @Deprecated
212
  public boolean hasTypeHandler(TypeReference<?> javaTypeReference, JdbcType jdbcType) {
213
    return javaTypeReference != null && getTypeHandler(javaTypeReference, jdbcType) != null;
×
214
  }
215

216
  public TypeHandler<?> getMappingTypeHandler(Class<? extends TypeHandler<?>> handlerType) {
217
    return allTypeHandlersMap.get(handlerType);
1✔
218
  }
219

220
  @Deprecated
221
  @SuppressWarnings("unchecked")
222
  public <T> TypeHandler<T> getTypeHandler(Class<T> clazz) {
223
    return (TypeHandler<T>) getTypeHandler((Type) clazz);
1✔
224
  }
225

226
  public TypeHandler<?> getTypeHandler(Type type) {
227
    return getTypeHandler(type, null);
1✔
228
  }
229

230
  @Deprecated
231
  public <T> TypeHandler<T> getTypeHandler(TypeReference<T> javaTypeReference) {
232
    return getTypeHandler(javaTypeReference, null);
1✔
233
  }
234

235
  public TypeHandler<?> getTypeHandler(JdbcType jdbcType) {
236
    return jdbcTypeHandlerMap.get(jdbcType);
1✔
237
  }
238

239
  @Deprecated
240
  public <T> TypeHandler<T> getTypeHandler(TypeReference<T> javaTypeReference, JdbcType jdbcType) {
241
    return (TypeHandler<T>) getTypeHandler(javaTypeReference.getRawType(), jdbcType);
1✔
242
  }
243

244
  public TypeHandler<?> getTypeHandler(Type type, JdbcType jdbcType, Class<? extends TypeHandler<?>> typeHandlerClass) {
245
    TypeHandler<?> typeHandler = getTypeHandler(type, jdbcType);
1✔
246
    if (typeHandler != null && (typeHandlerClass == null || typeHandler.getClass().equals(typeHandlerClass))) {
1✔
247
      return typeHandler;
1✔
248
    }
249
    if (typeHandlerClass == null) {
1✔
250
      typeHandler = getSmartHandler(type, jdbcType);
1✔
251
    } else {
252
      typeHandler = getMappingTypeHandler(typeHandlerClass);
1✔
253
      if (typeHandler == null) {
1✔
254
        typeHandler = getInstance(type, typeHandlerClass);
1✔
255
      }
256
    }
257
    return typeHandler;
1✔
258
  }
259

260
  public TypeHandler<?> getTypeHandler(Type type, JdbcType jdbcType) {
261
    if (ParamMap.class.equals(type)) {
1✔
262
      return null;
1✔
263
    }
264
    TypeHandler<?> handler = null;
1✔
265
    Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = getJdbcHandlerMap(type);
1✔
266

267
    if (Object.class.equals(type)) {
1✔
268
      if (jdbcHandlerMap != null) {
1!
NEW
269
        handler = jdbcHandlerMap.get(jdbcType);
×
270
      }
271
      if (handler == null) {
1!
272
        handler = jdbcTypeHandlerMap.get(jdbcType);
1✔
273
      }
274
      return handler != null ? handler : OBJECT_TYPE_HANDLER;
1✔
275
    }
276

277
    if (jdbcHandlerMap != null) {
1✔
278
      handler = jdbcHandlerMap.get(jdbcType);
1✔
279
      if (handler == null) {
1✔
280
        handler = jdbcHandlerMap.get(null);
1✔
281
      }
282
      if (handler == null) {
1✔
283
        // #591
284
        handler = pickSoleHandler(jdbcHandlerMap);
1✔
285
      }
286
    }
287
    if (handler == null) {
1✔
288
      handler = getSmartHandler(type, jdbcType);
1✔
289
    }
290
    if (handler == null && type instanceof ParameterizedType) {
1✔
291
      handler = getTypeHandler((Class<?>) ((ParameterizedType) type).getRawType(), jdbcType);
1✔
292
    }
293
    // type drives generics here
294
    return handler;
1✔
295
  }
296

297
  private TypeHandler<?> getSmartHandler(Type type, JdbcType jdbcType) {
298
    Entry<Constructor<?>, Set<JdbcType>> candidate = null;
1✔
299
    for (Entry<Type, Entry<Constructor<?>, Set<JdbcType>>> entry : smartHandlers.entrySet()) {
1✔
300
      Type registeredType = entry.getKey();
1✔
301
      if (registeredType.equals(type)) {
1✔
302
        candidate = entry.getValue();
1✔
303
        break;
1✔
304
      }
305
      if (registeredType instanceof Class) {
1✔
306
        if (type instanceof Class && ((Class<?>) registeredType).isAssignableFrom((Class<?>) type)) {
1!
307
          candidate = entry.getValue();
1✔
308
        }
309
      } else if (registeredType instanceof ParameterizedType) {
1!
310
        Class<?> registeredClass = (Class<?>) ((ParameterizedType) registeredType).getRawType();
1✔
311
        if (type instanceof ParameterizedType) {
1✔
312
          Class<?> clazz = (Class<?>) ((ParameterizedType) type).getRawType();
1✔
313
          if (registeredClass.isAssignableFrom(clazz)) {
1✔
314
            candidate = entry.getValue();
1✔
315
          }
316
        }
317
      }
318
    }
1✔
319
    if (candidate == null) {
1✔
320
      if (type instanceof Class) {
1✔
321
        Class<?> clazz = (Class<?>) type;
1✔
322
        if (Enum.class.isAssignableFrom(clazz)) {
1✔
323
          Class<?> enumClass = clazz.isAnonymousClass() ? clazz.getSuperclass() : clazz;
1!
324
          Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = getJdbcHandlerMapForEnumInterfaces(enumClass, enumClass);
1✔
325
          if (jdbcHandlerMap == null) {
1!
326
            TypeHandler<?> enumHandler = getInstance(enumClass, defaultEnumTypeHandler);
1✔
327
            register(enumClass, enumHandler);
1✔
328
            return enumHandler;
1✔
329
          }
330
        }
331
      }
332
      return null;
1✔
333
    }
334
    try {
335
      TypeHandler<?> typeHandler = (TypeHandler<?>) candidate.getKey().newInstance(type);
1✔
336
      register(type, jdbcType, typeHandler);
1✔
337
      return typeHandler;
1✔
NEW
338
    } catch (ReflectiveOperationException e) {
×
NEW
339
      throw new TypeException("Failed to invoke constructor " + candidate.getKey().toString(), e);
×
340
    }
341
  }
342

343
  private Map<JdbcType, TypeHandler<?>> getJdbcHandlerMap(Type type) {
344
    Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = typeHandlerMap.get(type);
1✔
345
    if (jdbcHandlerMap != null) {
1✔
346
      return NULL_TYPE_HANDLER_MAP.equals(jdbcHandlerMap) ? null : jdbcHandlerMap;
1✔
347
    }
348
    if (type instanceof Class) {
1✔
349
      Class<?> clazz = (Class<?>) type;
1✔
350
      if (!Enum.class.isAssignableFrom(clazz)) {
1✔
351
        jdbcHandlerMap = getJdbcHandlerMapForSuperclass(clazz);
1✔
352
      }
353
    }
354
    typeHandlerMap.put(type, jdbcHandlerMap == null ? NULL_TYPE_HANDLER_MAP : jdbcHandlerMap);
1✔
355
    return jdbcHandlerMap;
1✔
356
  }
357

358
  private Map<JdbcType, TypeHandler<?>> getJdbcHandlerMapForEnumInterfaces(Class<?> clazz, Class<?> enumClazz) {
359
    for (Class<?> iface : clazz.getInterfaces()) {
1✔
360
      Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = typeHandlerMap.get(iface);
1✔
361
      if (jdbcHandlerMap == null) {
1!
362
        jdbcHandlerMap = getJdbcHandlerMapForEnumInterfaces(iface, enumClazz);
1✔
363
      }
364
      if (jdbcHandlerMap != null) {
1!
365
        // Found a type handler registered to a super interface
UNCOV
366
        HashMap<JdbcType, TypeHandler<?>> newMap = new HashMap<>();
×
UNCOV
367
        for (Entry<JdbcType, TypeHandler<?>> entry : jdbcHandlerMap.entrySet()) {
×
368
          // Create a type handler instance with enum type as a constructor arg
UNCOV
369
          newMap.put(entry.getKey(), getInstance(enumClazz, entry.getValue().getClass()));
×
UNCOV
370
        }
×
UNCOV
371
        return newMap;
×
372
      }
373
    }
374
    return null;
1✔
375
  }
376

377
  private Map<JdbcType, TypeHandler<?>> getJdbcHandlerMapForSuperclass(Class<?> clazz) {
378
    Class<?> superclass = clazz.getSuperclass();
1✔
379
    if (superclass == null || Object.class.equals(superclass)) {
1✔
380
      return null;
1✔
381
    }
382
    Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = typeHandlerMap.get(superclass);
1✔
383
    if (jdbcHandlerMap != null) {
1✔
384
      return jdbcHandlerMap;
1✔
385
    }
386
    return getJdbcHandlerMapForSuperclass(superclass);
1✔
387
  }
388

389
  private TypeHandler<?> pickSoleHandler(Map<JdbcType, TypeHandler<?>> jdbcHandlerMap) {
390
    TypeHandler<?> soleHandler = null;
1✔
391
    for (TypeHandler<?> handler : jdbcHandlerMap.values()) {
1!
UNCOV
392
      if (soleHandler == null) {
×
UNCOV
393
        soleHandler = handler;
×
UNCOV
394
      } else if (!handler.getClass().equals(soleHandler.getClass())) {
×
395
        // More than one type handlers registered.
UNCOV
396
        return null;
×
397
      }
UNCOV
398
    }
×
399
    return soleHandler;
1✔
400
  }
401

402
  public void register(JdbcType jdbcType, TypeHandler<?> handler) {
403
    jdbcTypeHandlerMap.put(jdbcType, handler);
1✔
404
  }
1✔
405

406
  //
407
  // REGISTER INSTANCE
408
  //
409

410
  // Only handler
411

412
  public <T> void register(TypeHandler<T> typeHandler) {
413
    boolean mappedTypeFound = false;
1✔
414
    MappedTypes mappedTypes = typeHandler.getClass().getAnnotation(MappedTypes.class);
1✔
415
    if (mappedTypes != null) {
1!
416
      for (Class<?> handledType : mappedTypes.value()) {
×
417
        register(handledType, typeHandler);
×
418
        mappedTypeFound = true;
×
419
      }
420
    }
421
    if (!mappedTypeFound) {
1!
422
      Type detectedMappedType = TypeParameterResolver.resolveClassTypeParams(TypeHandler.class,
1✔
423
          typeHandler.getClass())[0];
1✔
424
      register(detectedMappedType, typeHandler);
1✔
425
    }
426
    if (!mappedTypeFound) {
1!
427
      register((Class<T>) null, typeHandler);
1✔
428
    }
429
  }
1✔
430

431
  // java type + handler
432

433
  public void register(Class<?> javaType, TypeHandler<?> typeHandler) {
434
    register((Type) javaType, typeHandler);
1✔
435
  }
1✔
436

437
  private void register(Type javaType, TypeHandler<?> typeHandler) {
438
    MappedJdbcTypes mappedJdbcTypes = typeHandler.getClass().getAnnotation(MappedJdbcTypes.class);
1✔
439
    if (mappedJdbcTypes != null) {
1!
UNCOV
440
      for (JdbcType handledJdbcType : mappedJdbcTypes.value()) {
×
UNCOV
441
        register(javaType, handledJdbcType, typeHandler);
×
442
      }
UNCOV
443
      if (mappedJdbcTypes.includeNullJdbcType()) {
×
UNCOV
444
        register(javaType, null, typeHandler);
×
445
      }
446
    } else {
447
      register(javaType, null, typeHandler);
1✔
448
    }
449
  }
1✔
450

451
  @Deprecated
452
  public <T> void register(TypeReference<T> javaTypeReference, TypeHandler<? extends T> handler) {
453
    register(javaTypeReference.getRawType(), handler);
1✔
454
  }
1✔
455

456
  // java type + jdbc type + handler
457

458
  public void register(Type javaType, JdbcType jdbcType, TypeHandler<?> handler) {
459
    if (javaType != null) {
1✔
460
      typeHandlerMap.compute(javaType, (k, v) -> {
1✔
461
        Map<JdbcType, TypeHandler<?>> map = (v == null || v == NULL_TYPE_HANDLER_MAP ? new HashMap<>() : v);
1✔
462
        map.put(jdbcType, handler);
1✔
463
        return map;
1✔
464
      });
465
      if (javaType instanceof ParameterizedType) {
1✔
466
        // MEMO: add annotation to skip this?
467
        Type rawType = ((ParameterizedType) javaType).getRawType();
1✔
468
        typeHandlerMap.compute(rawType, (k, v) -> {
1✔
469
          Map<JdbcType, TypeHandler<?>> map = (v == null || v == NULL_TYPE_HANDLER_MAP ? new HashMap<>() : v);
1!
470
          map.merge(jdbcType, handler, (handler1, handler2) -> handler1.equals(handler2) ? handler1
1!
471
              : new ConflictedTypeHandler((Class<?>) rawType, jdbcType, handler1, handler2));
1✔
472
          return map;
1✔
473
        });
474
      }
475
    }
476
    allTypeHandlersMap.put(handler.getClass(), handler);
1✔
477
  }
1✔
478

479
  //
480
  // REGISTER CLASS
481
  //
482

483
  // Only handler type
484

485
  public void register(Class<?> typeHandlerClass) {
486
    MappedTypes mappedTypes = typeHandlerClass.getAnnotation(MappedTypes.class);
1✔
487
    if (mappedTypes == null) {
1✔
488
      Type typeFromSignature = TypeParameterResolver.resolveClassTypeParams(TypeHandler.class, typeHandlerClass)[0];
1✔
489
      register(typeFromSignature, typeHandlerClass);
1✔
490
    } else {
1✔
491
      for (Class<?> javaTypeClass : mappedTypes.value()) {
1✔
492
        register(javaTypeClass, typeHandlerClass);
1✔
493
      }
494
    }
495
  }
1✔
496

497
  // java type + handler type
498

499
  public void register(String javaTypeClassName, String typeHandlerClassName) throws ClassNotFoundException {
500
    register(Resources.classForName(javaTypeClassName), Resources.classForName(typeHandlerClassName));
×
501
  }
×
502

503
  public void register(Type javaTypeClass, Class<?> typeHandlerClass) {
504
    // TODO: change the argument type to Class<? extends TypeHandler<?>> ?
505
    if (!TypeHandler.class.isAssignableFrom(typeHandlerClass)) {
1!
NEW
506
      throw new IllegalArgumentException(
×
NEW
507
          String.format("'%s' does not implement TypeHandler.", typeHandlerClass.getName()));
×
508
    }
509
    @SuppressWarnings("unchecked")
510
    Class<? extends TypeHandler<?>> clazz = (Class<? extends TypeHandler<?>>) typeHandlerClass;
1✔
511
    MappedJdbcTypes mappedJdbcTypes = typeHandlerClass.getAnnotation(MappedJdbcTypes.class);
1✔
512
    if (mappedJdbcTypes != null) {
1✔
513
      for (JdbcType handledJdbcType : mappedJdbcTypes.value()) {
1✔
514
        register(javaTypeClass, handledJdbcType, clazz);
1✔
515
      }
516
      if (mappedJdbcTypes.includeNullJdbcType()) {
1✔
517
        register(javaTypeClass, null, clazz);
1✔
518
      }
519
    } else {
520
      register(javaTypeClass, null, clazz);
1✔
521
    }
522
  }
1✔
523

524
  // java type + jdbc type + handler type
525

526
  public void register(Type javaTypeClass, JdbcType jdbcType, Class<?> typeHandlerClass) {
527
    @SuppressWarnings("unchecked")
528
    Class<? extends TypeHandler<?>> clazz = (Class<? extends TypeHandler<?>>) typeHandlerClass;
1✔
529
    for (Constructor<?> constructor : typeHandlerClass.getConstructors()) {
1✔
530
      if (constructor.getParameterCount() != 1) {
1✔
531
        continue;
1✔
532
      }
533
      Class<?> argType = constructor.getParameterTypes()[0];
1✔
534
      if (Type.class.equals(argType) || Class.class.equals(argType)) {
1!
535
        smartHandlers.computeIfAbsent(javaTypeClass, k -> {
1✔
536
          for (Entry<Constructor<?>, Set<JdbcType>> entry : smartHandlers.values()) {
1✔
537
            if (entry.getKey().equals(constructor)) {
1✔
538
              return entry;
1✔
539
            }
540
          }
1✔
541
          // Might have to Collections.synchronizedSet(new HashSet<>())
542
          return Map.entry(constructor, new HashSet<>());
1✔
543
        }).getValue().add(jdbcType);
1✔
544
        return;
1✔
545
      }
546
    }
547
    register(javaTypeClass, jdbcType, getInstance(javaTypeClass, typeHandlerClass));
1✔
548
  }
1✔
549

550
  // Construct a handler (used also from Builders)
551

552
  @SuppressWarnings("unchecked")
553
  public <T> TypeHandler<T> getInstance(Type javaTypeClass, Class<?> typeHandlerClass) {
554
    Constructor<?> c;
555
    try {
556
      if (javaTypeClass != null) {
1!
557
        try {
558
          c = typeHandlerClass.getConstructor(Type.class);
1✔
559
          return (TypeHandler<T>) c.newInstance(javaTypeClass);
1✔
560
        } catch (NoSuchMethodException ignored) {
1✔
561
        }
562
        if (javaTypeClass instanceof Class) {
1✔
563
          try {
564
            c = typeHandlerClass.getConstructor(Class.class);
1✔
565
            return (TypeHandler<T>) c.newInstance(javaTypeClass);
1✔
566
          } catch (NoSuchMethodException ignored) {
1✔
567
          }
568
        }
569
      }
570
      try {
571
        c = typeHandlerClass.getConstructor();
1✔
572
        return (TypeHandler<T>) c.newInstance();
1✔
NEW
573
      } catch (NoSuchMethodException e) {
×
NEW
574
        throw new TypeException("Unable to find a usable constructor for " + typeHandlerClass, e);
×
575
      }
NEW
576
    } catch (ReflectiveOperationException e) {
×
NEW
577
      throw new TypeException("Failed to invoke constructor for handler " + typeHandlerClass, e);
×
578
    }
579
  }
580

581
  // scan
582

583
  public void register(String packageName) {
584
    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
1✔
585
    resolverUtil.find(new ResolverUtil.IsA(TypeHandler.class), packageName);
1✔
586
    Set<Class<? extends Class<?>>> handlerSet = resolverUtil.getClasses();
1✔
587
    for (Class<?> type : handlerSet) {
1✔
588
      // Ignore inner classes and interfaces (including package-info.java) and abstract classes
589
      if (!type.isAnonymousClass() && !type.isInterface() && !Modifier.isAbstract(type.getModifiers())) {
1!
590
        register(type);
1✔
591
      }
592
    }
1✔
593
  }
1✔
594

595
  // get information
596

597
  /**
598
   * Gets the type handlers.
599
   *
600
   * @return the type handlers
601
   *
602
   * @since 3.2.2
603
   */
604
  public Collection<TypeHandler<?>> getTypeHandlers() {
605
    return Collections.unmodifiableCollection(allTypeHandlersMap.values());
×
606
  }
607

608
  public TypeHandler<?> resolve(Class<?> declaringClass, Type propertyType, String propertyName, JdbcType jdbcType,
609
      Class<? extends TypeHandler<?>> typeHandlerClass) {
610
    Type javaType = propertyType == null ? declaringClass : propertyType;
1✔
611
    return getTypeHandler(javaType, jdbcType, typeHandlerClass);
1✔
612
  }
613

614
}
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