如何在MyBatis中优雅的使用枚举

MyBatis提供了org.apache.ibatis.type.BaseTypeHandler类用于我们自己扩展类型转换器,上面的EnumTypeHandler和EnumOrdinalTypeHandler也都实现了这个接口

1. 定义接口

我们需要一个接口来确定某部分枚举类的行为。如下:

public interface BaseCodeEnum {

    int getCode();

}

该接口只有一个返回编码的方法,返回值将被存入数据库。

2. 改造枚举

public enum ValidStatus implements BaseCodeEnum {

    VALID(1), // 合法

    INVALID(-1); // 不合法

    private int code;

    ValidStatus(int code) {

        this.code = code;

    }

    @Override public int getCode() {

        return this.code;

    }

}     

3. 编写一个转换工具类

现在我们能顺利的将枚举转换为某个数值了,还需要一个工具将数值转换为枚举实例。

public class CodeEnumUtil

{

    public static & BaseCodeEnum> E codeOf(Class enumClass, int code)

    {

        E[] enumConstants = enumClass.getEnumConstants();

        for (E e : enumConstants)

        {

            if (e.getCode() == code) return e;

        }

        return null;

    }

}

4. 自定义类型转换器

准备工作做的差不多了,是时候开始编写转换器了。

BaseTypeHandler 一共需要实现4个方法:

void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType)

用于定义设置参数时,该如何把Java类型的参数转换为对应的数据库类型

T getNullableResult(ResultSet rs, String columnName)

用于定义通过字段名称获取字段数据时,如何把数据库类型转换为对应的Java类型

T getNullableResult(ResultSet rs, int columnIndex)

用于定义通过字段索引获取字段数据时,如何把数据库类型转换为对应的Java类型

T getNullableResult(CallableStatement cs, int columnIndex)

用定义调用存储过程后,如何把数据库类型转换为对应的Java类型

public class CodeEnumTypeHandler & BaseCodeEnum> extends BaseTypeHandler

{

    private Class type;

    public CodeEnumTypeHandler(Class type)

    {

        if (type == null)

        {

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

        }

        this.type = type;

    }

    @Override

    public void setNonNullParameter(PreparedStatement ps, int i, BaseCodeEnum parameter, JdbcType jdbcType)

    throws SQLException

    {

        ps.setInt(i, parameter.getCode());

    }

    @Override

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

    {

    int code = rs.getInt(columnName);

    return rs.wasNull() ? null : codeOf(code);

    }

    @Override

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

    {

        int code = rs.getInt(columnIndex);

        return rs.wasNull() ? null : codeOf(code);

    }

    @Override

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

    {

        int code = cs.getInt(columnIndex);

        return cs.wasNull() ? null : codeOf(code);

    }

    private E codeOf(int code)

    {

        try

        {

            return CodeEnumUtil.codeOf(type, code);

        }

        catch (Exception ex)

        {

            throw new IllegalArgumentException(

                "Cannot convert " + code + " to " + type.getSimpleName() + " by code value.", ex);

        }

    }

}

5. 优化

一旦系统中的枚举类多了起来,MyBatis的配置文件维护起来会变得非常麻烦,也容易出错。如何解决呢?

在Spring中我们可以使用JavaConfig方式来干预SqlSessionFactory的创建过程,来完成转换器的指定。

思路

再写一个能自动匹配转换行为的转换器

通过sqlSessionFactory.getConfiguration().getTypeHandlerRegistry()取得类型转换器注册器

再使用typeHandlerRegistry.setDefaultEnumTypeHandler(Class typeHandler)将第一步的转换器注册成为默认的

首先,我们需要一个能确定转换行为的转换器:

AutoEnumTypeHandler.java

public class AutoEnumTypeHandler> extends BaseTypeHandler

{

private BaseTypeHandler typeHandler = null;

public AutoEnumTypeHandler(Class type)

{

if (type == null)

{

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

}

if (BaseCodeEnum.class.isAssignableFrom(type))

{

// 如果实现了 BaseCodeEnum 则使用我们自定义的转换器

typeHandler = new CodeEnumTypeHandler(type);

}

else

{

// 默认转换器 也可换成 EnumOrdinalTypeHandler

typeHandler = new EnumTypeHandler<>(type);

}

}

@Override

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

{

typeHandler.setNonNullParameter(ps, i, parameter, jdbcType);

}

@Override

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

{

return (E) typeHandler.getNullableResult(rs, columnName);

}

@Override

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

{

return (E) typeHandler.getNullableResult(rs, columnIndex);

}

@Override

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

{

return (E) typeHandler.getNullableResult(cs, columnIndex);

}

}

接下来,我们需要干预SqlSessionFactory的创建过程,将刚刚的转换器指定为默认的:

@Bean

public SqlSessionFactory sqlSessionFactoryBean() throws Exception

{

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

sqlSessionFactoryBean.setDataSource(dataSource());

SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();

// 取得类型转换注册器

TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry();

// 注册默认枚举转换器

typeHandlerRegistry.setDefaultEnumTypeHandler(AutoEnumTypeHandler.class);

return sqlSessionFactory;

}

搞定! 这样一来,如果枚举实现了BaseCodeEnum接口就使用我们自定义的CodeEnumTypeHandler,如果没有实现BaseCodeEnum接口就使用默认的。再也不用写MyBatis的配置文件了!

你可能感兴趣的:(如何在MyBatis中优雅的使用枚举)