Skip to content

Instantly share code, notes, and snippets.

@xuyecan
Created October 10, 2018 04:44
Show Gist options
  • Save xuyecan/389bf9afd873b195c369d22a41d9e084 to your computer and use it in GitHub Desktop.
Save xuyecan/389bf9afd873b195c369d22a41d9e084 to your computer and use it in GitHub Desktop.
mybatis enum handler
public class CodeEnumTypeHandler<E extends Enum<E> & CodeEnum> extends BaseTypeHandler<CodeEnum>
{
private Class<E> type;
public CodeEnumTypeHandler(Class<E> type) {
if (type == null) {
throw new IllegalArgumentException("Type argument cannot be null");
}
this.type = type;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, CodeEnum parameter, JdbcType jdbcType)
throws SQLException {
ps.setInt(i, parameter.getCode());
}
@Override
public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
int code = rs.getInt(columnName);
return rs.wasNull() ? null : codeOf(code);
}
@Override
public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
int code = rs.getInt(columnIndex);
return rs.wasNull() ? null : codeOf(code);
}
@Override
public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
int code = cs.getInt(columnIndex);
return cs.wasNull() ? null : codeOf(code);
}
private E codeOf(int code){
try {
return CodeEnumUtil.codeOf(type, code);
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot convert " + code + " to " + type.getSimpleName() + " by code value.", ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment