Create a gist now

Instantly share code, notes, and snippets.

anonymous /gist:170191
Created Aug 19, 2009

What would you like to do?
Apache iBatis enum type handler
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment