Mybatis TypeHandler类型转换

定义一个枚举类

public enum KbnEnum {
    
    UNAUDITED(0, "未审核"),
    AUDIT(1, "待审核"),
    AUDITED(2, "已审核");

    private int code;
    public int getCode() {
        return code;
    }

    private String name;
    public String getName() {
        return name;
    }

    KbnEnum(int code, String name) {
        this.code = code;
        this.name = name;
    }
    
    public static KbnEnum fromCode(int code) {

        for (KbnEnum item : KbnEnum.values()) {
            if (item.code == code) {
                return item;
            }
        }

        return null;
    }
}

定义一个类型转换器

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
// 导入我们自定义的枚举类
import com.xxx.KbnEnum;

// 数据库字段所对应的类型
@MappedJdbcTypes({JdbcType.NUMERIC})
// 需要转换为JAVA侧的类型
@MappedTypes(value = KbnEnum.class)
// 进行类型转换需要继承Mybatis的BaseTypeHandler类
public class CustomEnumTypeHandler extends BaseTypeHandler<KbnEnum> {
    
    // 重写BaseTypeHandler中的方法
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, KbnEnum parameter, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i, parameter.getCode());
    }

    @Override
    public KbnEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String code = resultSet.getString(s);
        return KbnEnum.fromCode(Integer.valueOf(code));
    }

    @Override
    public KbnEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String code = resultSet.getString(i);
        return KbnEnum.fromCode(Integer.valueOf(code));
    }

    @Override
    public KbnEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String code = callableStatement.getString(i);
        return KbnEnum.fromCode(Integer.valueOf(code));
    }
}

将自定义转换器添加到Mybatis转换器中
⏹方式1,在SpringBoot的配置文件中声明

mybatis.type-handlers-package=com.xxx.xxx.config

⏹方式2,在进行类型映射的时候,手动指定转换器

<resultMap id="userResultMap" type="com.xxx.dto.TestDto">
    <result column="JHE_KEIYAKUKBN" property="kbnEnum" typeHandler="com.xxx.config.CustomEnumTypeHandler" />
</resultMap>
<select id="testT" resultMap="userResultMap">
SELECT 
    JHE_KEIYAKUKBN
FROM
    JUHEDF
WHERE
    JHE_SIMEINO = 1
</select>

查询
可以看到成功将数字0封装为枚举类
在这里插入图片描述

参考资料

  1. 👍👍👍https://blog.csdn.net/lmb55/article/details/90380309
  2. https://zhuanlan.zhihu.com/p/245448322
  3. http://www.itsoku.com/article/194
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值