1+ package cl .bennu .commons .enums .handler ;
2+
3+ import cl .bennu .commons .enums .base .BaseEnum ;
4+ import cl .bennu .commons .exception .NoDataException ;
5+ import org .apache .ibatis .type .JdbcType ;
6+ import org .apache .ibatis .type .MappedTypes ;
7+ import org .apache .ibatis .type .TypeHandler ;
8+
9+ import java .sql .*;
10+
11+ @ MappedTypes (BaseEnum .class )
12+ public class EnumTypeHandler <T > implements TypeHandler <BaseEnum > {
13+
14+ private final Class <T > clazz ;
15+
16+ public EnumTypeHandler (Class <T > clazz ) throws NoDataException {
17+ if (clazz == null ) throw new NoDataException ("No class defined" );
18+ this .clazz = clazz ;
19+ }
20+
21+ public BaseEnum findEnum (Integer id ) {
22+ BaseEnum [] enums = (BaseEnum []) clazz .getEnumConstants ();
23+ for (BaseEnum baseEnum : enums ) {
24+ if (baseEnum .getId ().equals (id )) {
25+ return baseEnum ;
26+ }
27+ }
28+ return null ;
29+ }
30+
31+ @ Override
32+ public void setParameter (PreparedStatement ps , int i , BaseEnum parameter , JdbcType jdbcType ) throws SQLException {
33+ if (parameter == null ) {
34+ ps .setNull (i , Types .INTEGER );
35+ } else {
36+ ps .setInt (i , parameter .getId ());
37+ }
38+ }
39+
40+ @ Override
41+ public BaseEnum getResult (ResultSet rs , String columnName ) throws SQLException {
42+ int value = rs .getInt (columnName );
43+ return value == 0 ? null : findEnum (value );
44+ }
45+
46+ @ Override
47+ public BaseEnum getResult (ResultSet rs , int columnIndex ) throws SQLException {
48+ int value = rs .getInt (columnIndex );
49+ return value == 0 ? null : findEnum (value );
50+ }
51+
52+ @ Override
53+ public BaseEnum getResult (CallableStatement cs , int columnIndex ) throws SQLException {
54+ int value = cs .getInt (columnIndex );
55+ return value == 0 ? null : findEnum (value );
56+ }
57+ }
0 commit comments