Created
August 19, 2009 05:41
-
-
Save anonymous/170191 to your computer and use it in GitHub Desktop.
Apache iBatis enum type handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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