Refer: http://opensource.atlassian.com/confluence/oss/display/IBATIS/How+do+I+use+a+Custom+Type+Handler+with+complex+property+or+Type+Safe+Enumeration
这个实现给每个Enum对象一个数字值,所以可以把这个数字值存入到数据库中,或者从数据库中取出这个数字值然后恢复这个Enum对象。
1、定义一个所以 Enum的interface
package com.demo;
public interface HasValueInterface {
public Integer getValue();
}
2、定义一个Enum类型
package com.demo;
public enum Status implements HasValueInterface{
ALL(0),
GOOD(1),
BAD(2);
private final int status;
Status(int status) {
this.status = status;
}
public Integer getValue() {
return status;
}
}
3、定义一个抽象的typehandler
package com.demo;
import java.sql.SQLException;
import java.sql.Types;
import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;
import com.demo.HasValueInterface;
public abstract class HasValueTypeHandler implements TypeHandlerCallback {
public abstract HasValueInterface[] getEnums();
public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
if (parameter == null) {
setter.setNull(Types.INTEGER);
} else {
HasValueInterface status = (HasValueInterface) parameter;
setter.setInt(status.getValue());
}
}
public Object getResult(ResultGetter getter) throws SQLException {
/*千万要注意!!!
* When calling getter.getNull before actually getting the column's value (getter.getInt(),
* getNull() will always return true, since no value has been fetched yet.
* The check for null has to be done after getting the value.
*/
int value = getter.getInt();
if (getter.wasNull())
return null;
for (HasValueInterface status : getEnums()) {
if (status.getValue().equals(value)) {
return status;
}
}
throw new UnsupportedOperationException("No such status");
}
public Object valueOf(String s) {
return s;
}
}
4、给Status实现一个typehandler
package com.demo;
import com.demo.Status;
import com.demo.HasValueInterface;
public class StatusTypeHandler extends HasValueTypeHandler {
public HasValueInterface[] getEnums() {
return Status.values();
}
}