springboot+mybatis 實現自定義枚舉類型的處理


自定義的枚舉類要實現接口IBaseEnum<T>。它的代碼如下:

@JsonSerialize(using = JsonEnumSerializer.class) // json序列化
public interface IBaseEnum<T> extends Serializable {

    T getValue();
    String getLabel();
}

一、枚舉類型數據返回前端的處理

對枚舉類序列化的實現

/**
 * @author shipc 2019/12/31 10:42
 * @version 1.0.0
 */
public class JsonEnumSerializer extends JsonSerializer<IBaseEnum> {

    private static Logger log = LoggerFactory.getLogger(JsonEnumSerializer.class);
    @Override
    public void serialize(IBaseEnum iBaseEnum, JsonGenerator jsonGenerator, SerializerProvider serializerProvider){
        HashMap<String, Object> map = new HashMap<>();
        map.put("value", iBaseEnum.getValue());
        map.put("label", iBaseEnum.getLabel());
        try {
            serializerProvider.defaultSerializeValue(map, jsonGenerator);
        } catch (IOException e) {
            log.error("枚舉類序列化錯誤", e);
            throw new BaseException(BaseResultCode.SERIALIZER_ERROR);
        }
    }
}

使用: 實現IBaseEnum<T>, 直接返回枚舉對象。

示例:

public enum ApplyType implements IBaseEnum<Integer> {
    AUTO(1, "自動申請"),
    MANUAL(0, "手動申請");
    // 省略了其他代碼
}

返回數據:

{
    "success": true,
    "code": "0000000",
    "message": "成功",
    "data": {
        "label": "自動申請",
        "value": 1
    }
}

二、枚舉類型存入數據庫的處理

1.首先需要實現IBaseEnum<T>接口;

2.其次要將具體的類加到BaseEnumHandler類@MappedTypes(value = {})中。如面代碼ApplyType.class,RepairOrderStatus.class, ConsumableOrderStatus.class,一樣;

/**
 * @author shipc 2019/12/31 14:06
 * @version 1.0.0
 */
@MappedTypes(value = {RepairOrderStatus.class, ConsumableOrderStatus.class, ApplyType.class})
public class BaseEnumHandler<T extends IBaseEnum> extends BaseTypeHandler<T> {
    private Class<T> type;
    private T[] enums;

    public BaseEnumHandler(Class<T> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
        this.enums = type.getEnumConstants();

    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, T t, JdbcType jdbcType) throws SQLException {
        if (jdbcType == null) {
            preparedStatement.setString(i, t.getValue().toString());
        } else {
            preparedStatement.setObject(i, t.getValue(), jdbcType.TYPE_CODE);
        }
    }

    @Override
    public T getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return getEnumByValue(resultSet.getObject(s));
    }

    private T getEnumByValue(Object object) {
        if (object == null) return null;
        for (T t : enums) {
            if (t.getValue().equals(object) || t.getValue().toString().equals(object.toString())) {
                return t;
            }
        }
        return null;
    }

    @Override
    public T getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return getEnumByValue(resultSet.getObject(i));
    }

    @Override
    public T getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return getEnumByValue(callableStatement.getObject(i));
    }

    public Class<T> getType() {
        return type;
    }

    public void setType(Class<T> type) {
        this.type = type;
    }

    public T[] getEnums() {
        return enums;
    }

    public void setEnums(T[] enums) {
        this.enums = enums;
    }
}

3.最后要在mapper文件中對應字段的位置配置jdbcType和typeHandler,如下方訂單狀態:

order_state = #{item,jdbcType=INTEGER,typeHandler=com.rayootech.system.mybatis.handler.BaseEnumHandler}

這樣存入數據庫的值就是枚舉類value的值。

三、從數據庫查出是枚舉類型的處理

這和“枚舉類型存入數據庫的處理”的前兩步是一樣的。

最后一步是要定義一個<resultMap>,在枚舉類型對應的<result>中配置javaType和typeHandler,如下面代碼ApplyType所示:

<result property="applyType" column="ot_apply_type" javaType="com.rayootech.system.domain.consumable.ApplyType"
        typeHandler="com.rayootech.system.mybatis.handler.BaseEnumHandler"/>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM