TypeHandler转换指定数据库中数据为Enum枚举

mysql 专栏收录该内容
2 篇文章 0 订阅

1.创建一个枚举类

package com.robin.test.demo.entiry;

import lombok.Getter;

public enum  TypeEnum {

    ONE(1),

    TWO(2),

    THREE(3);

    @Getter
    private Integer level;

    TypeEnum(Integer level){
        this.level = level;
    }
    public static TypeEnum getByLevel(int level){
        TypeEnum[] typeEnums = TypeEnum.values();
        for (TypeEnum typeEnum : typeEnums) {
            if (typeEnum.getLevel() == level){
                return typeEnum;
            }
        }
        return null;
    }

}

2.在实体类中添加枚举属性

package com.robin.test.demo.entiry;

import lombok.Data;

@Data
public class Student {
    //姓名
    private String name;
    //年龄
    private Integer age;
    //等级
    private TypeEnum type;
    public Student() {
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

3.创建handle

package com.robin.test.demo.config;

import com.robin.test.demo.entiry.TypeEnum;
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 java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes({JdbcType.INTEGER})
@MappedTypes(TypeEnum.class)
public class CreditAmountTypeHandle extends BaseTypeHandler<TypeEnum> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, TypeEnum typeEnum, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i,typeEnum.getLevel());
    }

    @Override
    public TypeEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
        int level = resultSet.getInt(s);
        return level == 0 && resultSet.wasNull()?null:TypeEnum.getByLevel(level);

    }

    @Override
    public TypeEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
        int level = resultSet.getInt(i);
        return level == 0 && resultSet.wasNull()?null:TypeEnum.getByLevel(level);
    }

    @Override
    public TypeEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        int level = callableStatement.getInt(i);
        return level == 0 && callableStatement.wasNull()?null:TypeEnum.getByLevel(level);
    }
}

4.在yml中指定handle路径

mybatis:
  mapper-locations: classpath:mapper/*.xml # 配置 Mapper XML 地址
  type-handlers-package: com.robin.test.demo.config
  • 0
    点赞
  • 1
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值