如何在mybatis中获取枚举描述,当序列化为JSON字符串时



问题是在序列化为JSON字符串时如何在mybatis中获得枚举描述

mybatis可以很好地获取枚举属性,也可以很好的通过Model获取描述值。DocFlowEnum.getStateName((

但是在序列化为JSON字符串时,如何获得描述值this is a draft而不是普通值Draft

因为它是一个列表,我不想循环手动设置描述值

DocFlowEnum,DocFlowEnumTypeHandler,模型

这是带有描述的枚举

public enum DocFlowEnum{
Draft(0, "this is a draft"),
ToProcess(1, "this is to process"),
InProcess(2, "this is in process"),
private static final Map<Integer, DocFlowEnum> byState = new HashMap<>();
static {
for (DocFlowEnum e : DocFlowEnum.values()) {
if (byState.put(e.getState(), e) != null) {
throw new IllegalArgumentException("duplicate state: " + e.getState());
}
}
}
public static DocFlowEnum getByState(Integer state) {
return byState.get(state);
}
// original code follows
private final String stateName;
private final Integer state;
DocFlowEnum(Integer state, String stateName) {
this.state = state;
this.stateName = stateName;
}
public Integer getState() {
return state;
}
public String getStateName() {
return stateName;
}
}

这是mybatis的TypeHandler

@MappedJdbcTypes(JdbcType.INTEGER)
@MappedTypes(value = DocFlowEnum.class)
public class DocFlowEnumTypeHandler extends BaseTypeHandler<DocFlowEnum> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, DocFlowEnum userStateEnum, JdbcType jdbcType) throws SQLException {
preparedStatement.setInt(i,userStateEnum.getState());
}
@Override
public DocFlowEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
int code =resultSet.getInt(s);
if(code>=0&&code<=5){
return DocFlowEnum.getByState(code);
}
return null;
}
@Override
public DocFlowEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
int code = resultSet.getInt(i);
if(code>=0&&code<=5){
return DocFlowEnum.getByState(code);
}
return null;
}
@Override
public DocFlowEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
int code = callableStatement.getInt(i);
if(code>=0&&code<=5){
return DocFlowEnum.getByState(code);
}
return null;
}
}

这是模型

@Data
public class Document{
private DocFlowEnum stateEnum;
}

非常感谢所有提供帮助的人

好的,30分钟后,我找到了解决方案。太容易了。

@JsonValue
public String getStateName() {
return stateName;
}

也许这可以帮助其他人。

最新更新