在 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 中的映射和轉換。