public interface BasicCodeEnum {
/**
* 獲取枚舉值
*
* @return 枚舉值
*/
Integer getValue();
}
@MappedTypes(value = {Status.class})
@MappedJdbcTypes(JdbcType.TINYINT)
public class MyConvertTypeHandler<E extends Enum<E> & BasicCodeEnum> extends BaseTypeHandler<BasicCodeEnum> {
private Class<E> type;
public MyConvertTypeHandler(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, BasicCodeEnum parameter, JdbcType jdbcType)
throws SQLException {
ps.setInt(i, parameter.getValue());
}
@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 codeOf(type, code);
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot convert " + code + " to " + type.getSimpleName() + " by code value.", ex);
}
}
public static <E extends Enum<?> & BasicCodeEnum> E codeOf(Class<E> enumClass, int code) {
E[] enumConstants = enumClass.getEnumConstants();
for (E e : enumConstants) {
if (e.getValue() == code)
return e;
}
return null;
}
}