Anonymous (owner)

Revisions

  • 7dda72 Tue Aug 18 22:41:44 -0700 2009
gist: 170191 Download_button fork
public
Description:
Apache iBatis enum type handler
Public Clone URL: git://gist.github.com/170191.git
Embed All Files: show embed
Java #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
 
import org.apache.commons.lang.StringUtils;
 
import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;
 
/**
* @see http://opensource.atlassian.com/confluence/oss/display/IBATIS/How+do+I+use+Enums+with+annotations
*/
public class EnumTypeHandlerImpl implements TypeHandlerCallback {
 
private int jdbcType;
private Map<String, ValueEnum> map = new HashMap<String, ValueEnum>();
 
protected EnumTypeHandlerImpl() {
if (this.getClass().isAnnotationPresent(EnumTypeHandler.class)){
EnumTypeHandler eth = this.getClass().getAnnotation(EnumTypeHandler.class);
jdbcType = eth.jdbcType();
for (ValueEnum e : (ValueEnum[]) eth.enumClass().getEnumConstants()){
map.put(e.toString(), e);
if (StringUtils.isNotEmpty(e.getDefaultValue())) {
map.put(e.getDefaultValue(), e);
}
if (e.getOtherValues() != null) {
for (String key : e.getOtherValues()) {
map.put(key, e);
}
}
}
} else {
throw new RuntimeException("Must provide @EnumTypeHandler annotation.");
}
}
 
public Object getResult(ResultGetter resultGetter) throws SQLException {
if (resultGetter.wasNull()) {
return null;
}
return map.get(resultGetter.getObject());
}
 
public void setParameter(ParameterSetter parameterSetter, Object object) throws SQLException {
if (object == null) {
parameterSetter.setNull(jdbcType);
} else {
ValueEnum e = (ValueEnum) object;
parameterSetter.setObject(StringUtils.isNotEmpty(e.getDefaultValue()) ? e.getDefaultValue() : e.toString(), jdbcType);
}
}
 
public Object valueOf(String string) {
return string;
}
}