在 MyBatis 中处理 Enum 类型可以通过以下几种方式来优雅地实现:
public class MyEnumTypeHandler extends BaseTypeHandler<MyEnum> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, MyEnum parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.name());
}
@Override
public MyEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
String value = rs.getString(columnName);
return value != null ? MyEnum.valueOf(value) : null;
}
@Override
public MyEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String value = rs.getString(columnIndex);
return value != null ? MyEnum.valueOf(value) : null;
}
@Override
public MyEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String value = cs.getString(columnIndex);
return value != null ? MyEnum.valueOf(value) : null;
}
}
然后在 MyBatis 的配置文件中注册该 TypeHandler:
<typeHandlers>
<typeHandler handler="com.example.MyEnumTypeHandler"/>
</typeHandlers>
<resultMap id="myResultMap" type="com.example.MyEntity">
<id property="id" column="id"/>
<result property="myEnum" column="my_enum" typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
</resultMap>
@Data
@TableName("my_table")
public class MyEntity {
@TableId
private Long id;
@TableField(typeHandler = EnumTypeHandler.class)
@EnumType(EnumHandler.class)
private MyEnum myEnum;
}
public enum MyEnum {
VALUE1,
VALUE2
}
public class EnumHandler extends IEnumHandler<MyEnum> {
@Override
public Object getValue(MyEnum enumObj, String s) {
return enumObj.name();
}
@Override
public MyEnum getResult(Object o, String s) {
return MyEnum.valueOf((String) o);
}
}
通过以上几种方式,可以优雅地处理 Enum 类型在 MyBatis 中的映射和转换。