mybatis 對枚舉類型的自動轉換

支持對mybatis轉對象過程當中枚舉類型自動轉換. java

聲明: 最近發佈的文章都是從已經上線的項目中分離的, 絕對經得起考驗. 若有問題, 歡迎留言. 謝謝!mysql

EnumTypeHandler.javagit

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<E extends Enum<?> & BaseEnum<Integer>> extends BaseTypeHandler<BaseEnum<Integer>> {

    private Class<E> type;

    public EnumTypeHandler() { }

    /**
     * 設置配置文件設置的轉換類以及枚舉類內容
     * @param type 配置文件中設置的轉換類
     */
    public EnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BaseEnum<Integer> 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中置頂轉換github

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 全局參數 -->
    <settings>
        <!-- 使全局的映射器啓用或禁用緩存。 -->
        <setting name="cacheEnabled" value="true"/>
        <!-- 全局啓用或禁用延遲加載。當禁用時,全部關聯對象都會即時加載。 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 當啓用時,有延遲加載屬性的對象在被調用時將會徹底加載任意屬性。不然,每種屬性將會按須要加載。 -->
        <setting name="aggressiveLazyLoading" value="true"/>
        <!-- 是否容許單條sql 返回多個數據集  (取決於驅動的兼容性) default:true -->
        <setting name="multipleResultSetsEnabled" value="true"/>
        <!-- 是否能夠使用列的別名 (取決於驅動的兼容性) default:true -->
        <setting name="useColumnLabel" value="true"/>
        <!-- 容許JDBC 生成主鍵。須要驅動器支持。若是設爲了true,這個設置將強制使用被生成的主鍵,有一些驅動器不兼容不過仍然能夠執行。  default:false  -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- 指定 MyBatis 如何自動映射 數據基表的列 NONE:不隱射 PARTIAL:部分  FULL:所有  -->
        <setting name="autoMappingBehavior" value="PARTIAL"/>
        <!-- 這是默認的執行類型  (SIMPLE: 簡單; REUSE: 執行器可能重複使用prepared statements語句;BATCH: 執行器能夠重複執行語句和批量更新)  -->
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <!-- 使用駝峯命名法轉換字段。 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 設置本地緩存範圍 session:就會有數據的共享  statement:語句範圍 (這樣就不會有數據的共享 ) defalut:session -->
        <setting name="localCacheScope" value="SESSION"/>
        <!-- 設置但JDBC類型爲空時,某些驅動程序 要指定值,default:OTHER,插入空值時不須要指定類型 -->
        <setting name="jdbcTypeForNull" value="NULL"/>
    </settings>

    <typeHandlers>
        <typeHandler handler="com.xxx.xxx.config.mybatis.EnumTypeHandler" jdbcType="NUMERIC" javaType="com.xxx.xxx.enums.StatusEnum" />
    </typeHandlers>

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql"/>
            <property name="offsetAsPageNum" value="false"/>
            <property name="rowBoundsWithCount" value="false"/>
            <property name="pageSizeZero" value="true"/>
            <property name="reasonable" value="false"/>
            <property name="supportMethodsArguments" value="false"/>
            <property name="returnPageInfo" value="none"/>
        </plugin>
    </plugins>
</configuration>

oksql

相關文章
相關標籤/搜索