mybatis mysql enum_mybatis 对枚举类型的自动转换

支持对mybatis转对象过程中枚举类型自动转换.

声明: 最近发布的文章都是从已经上线的项目中分离的, 绝对经得起考验. 如有问题, 欢迎留言. 谢谢!

EnumTypeHandler.java

package com.xxx.xxx.config.mybatis;

import com.xxx.xxx.enums.BaseEnum;

import lombok.extern.slf4j.Slf4j;

import org.apache.ibatis.type.*;

import java.sql.CallableStatement;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

/**

* mybatis枚举类型处理

* org.apache.ibatis.type.EnumOrdinalTypeHandler

* org.apache.ibatis.type.EnumTypeHandler

* @author Yehun

*/

@Slf4j

@MappedJdbcTypes(value = {JdbcType.NUMERIC, JdbcType.INTEGER})

public class EnumTypeHandler & BaseEnum> extends BaseTypeHandler> {

private Class type;

public EnumTypeHandler() { }

/**

* 设置配置文件设置的转换类以及枚举类内容

* @param type 配置文件中设置的转换类

*/

public EnumTypeHandler(Class type) {

if (type == null) {

throw new IllegalArgumentException("Type argument cannot be null");

}

this.type = type;

}

@Override

public void setNonNullParameter(PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType) throws SQLException {

Integer code = parameter.getCode();

if (jdbcType == null && code != null) {

ps.setInt(i, code);

} else {

assert jdbcType != null;

ps.setObject(i, parameter.getCode(), jdbcType.TYPE_CODE); // see r3589

}

}

@Override

public E getNullableResult(ResultSet rs, String columnName) throws SQLException {

Integer i = rs.getInt(columnName);

return rs.wasNull() ? null : getEnum(i);

}

@Override

public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {

Integer i = rs.getInt(columnIndex);

return rs.wasNull() ? null : getEnum(i);

}

@Override

public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {

Integer i = cs.getInt(columnIndex);

return cs.wasNull() ? null : getEnum(i);

}

/**

* 枚举类型转换,由于构造函数获取了枚举的子类enums

* @param value 数据库中存储的自定义value属性

* @return value对应的枚举类

*/

private E getEnum(Integer value) {

log.debug("enum is [{}]", this.type.getName());

E[] enums = this.type.getEnumConstants();

if(enums != null) {

for (E e : enums) {

if (e.getCode().equals(value)) {

return e;

}

}

}

throw new IllegalArgumentException(String.format("未知的枚举类型:%s,请核对%s", value, type.getSimpleName()));

}

}

在mybatis-config.xml中置顶转换

ok

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值