Mybatis 映射自定义枚举类

场景:映射字段是枚举类,而枚举的属性是自定义属性,这就不能用

EnumOrdinalTypeHandler和EnumTypeHandler作为处理器了,需要自定义处理器。

上代码:

1.新增基础接口类:

public interface BaseEnum {
    int getCode();
}

2.枚举类继承该类,属性约定为code

public enum Sex implements BaseEnum {
    MALE(0), FEMALE(1);

    private int code;
    Sex(int code){
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

3.自定义类型处理器,继承BaseTypeHandler,注意,注解为@MappedJdbcTypes,指定java需要转换的jdbc类型

@MappedJdbcTypes(JdbcType.INTEGER)
public class CodeEnumTypeHandler<E extends Enum<?> & BaseEnum> extends BaseTypeHandler<BaseEnum> {

    private Class<E> type;

    public CodeEnumTypeHandler(){}

    public CodeEnumTypeHandler(Class<E> type) {
        if(type == null){
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, BaseEnum baseEnum, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i, baseEnum.getCode());
    }

    @Override
    public BaseEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
        int code = resultSet.getInt(s);
        return resultSet.wasNull() ? null: codeOf(code);
    }

    @Override
    public BaseEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
        int code = resultSet.getInt(i);
        return resultSet.wasNull() ? null: codeOf(code);
    }

    @Override
    public BaseEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        int code = callableStatement.getInt(i);
        return callableStatement.wasNull() ? null: codeOf(code);
    }

    private E codeOf(int code){
        try{
            return CodeEnumUtil.codeOf(type, code);
        }catch (Exception e){
            throw new IllegalArgumentException("Cannot convert "+ code + " to "+ type.getSimpleName() + " by code value.", e);
        }
    }
}

4.实体类的枚举字段(ps:试过这里不写也可以)

    /**
     * 性别(0:女性,1:男性)
     */
    @TableField(value = "SEX",typeHandler = CodeEnumTypeHandler.class)
    private Sex sex;

5.application.yml注册处理器

mybatis-plus:
      type-handlers-package: com.creativediary.user.handler

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值