View Javadoc
1   /*
2    *    Copyright 2009-2023 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.submitted.typehandlerinjection;
17  
18  import java.sql.CallableStatement;
19  import java.sql.PreparedStatement;
20  import java.sql.ResultSet;
21  import java.sql.SQLException;
22  import java.util.HashMap;
23  import java.util.Map;
24  import java.util.Map.Entry;
25  
26  import org.apache.ibatis.type.JdbcType;
27  import org.apache.ibatis.type.TypeHandler;
28  
29  public class UserStateTypeHandler<E> implements TypeHandler<Object> {
30  
31    private static final Map<String, String> lookup;
32  
33    static {
34      lookup = new HashMap<>();
35      lookup.put("0", "INACTIVE");
36      lookup.put("1", "ACTIVE");
37    }
38  
39    UserStateTypeHandler() {
40      // can only be constructed from this package
41    }
42  
43    @Override
44    public Object getResult(ResultSet rs, String arg) throws SQLException {
45      return lookupValue(rs.getInt(arg));
46    }
47  
48    @Override
49    public Object getResult(ResultSet rs, int arg) throws SQLException {
50      return lookupValue(rs.getInt(arg));
51    }
52  
53    @Override
54    public Object getResult(CallableStatement cs, int arg) throws SQLException {
55      return lookupValue(cs.getInt(arg));
56    }
57  
58    @Override
59    public void setParameter(PreparedStatement ps, int i, Object value, JdbcType jdbcType) throws SQLException {
60  
61      String key = "";
62      for (Entry<String, String> entry : lookup.entrySet()) {
63        if (value.equals(entry.getValue())) {
64          key = entry.getKey();
65        }
66      }
67      ps.setInt(i, Integer.parseInt(key));
68    }
69  
70    private String lookupValue(int val) {
71      return lookup.get(String.valueOf(val));
72    }
73  }