亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

mybatis-plus enum實(shí)現(xiàn)枚舉類型自動(dòng)轉(zhuǎn)換

 更新時(shí)間:2024年07月25日 09:59:41   作者:xy294636185  
本文主要介紹了mybatis-plus enum實(shí)現(xiàn)枚舉類型自動(dòng)轉(zhuǎn)換,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

mybatis-plus實(shí)現(xiàn)了對(duì)“實(shí)體類指定了枚舉類型,想查詢時(shí)返回的是枚舉值而非value值”,“插入數(shù)據(jù)時(shí),實(shí)體賦值的是枚舉類型,想入庫(kù)時(shí)插入對(duì)應(yīng)的value值”,“不想寫其他的handler處理程序,希望能夠自動(dòng)處理”。

mybatis-plus對(duì)于上述的訴求都可以滿足,簡(jiǎn)單的處理方案是:

* 1、實(shí)現(xiàn) IEnum of T
* 2、注解 @EnumValue,不用實(shí)現(xiàn) IEnum of T

具體的官方文檔為 https://mp.baomidou.com/guide/enum.html

定義一個(gè)簡(jiǎn)單實(shí)體

先定義一個(gè)示例實(shí)體類,我們?cè)趯?shí)體Demo中用到了DemoStatusEnum

/**
 * 實(shí)體類
 */
@Data
@TableName("demo")
public class Demo extends Model<Demo> {
    @TableField("status")
    private DemoStatusEnum status;    
}

DemoStatusEnum枚舉定義

我們采用了官方提到的兩種方式的第一種:即實(shí)現(xiàn)IEnum<T>

/**
 * 支持枚舉值的兩種方式
 * 1、實(shí)現(xiàn) IEnum of T
 * 2、注解 @EnumValue,不用實(shí)現(xiàn) IEnum of T
 */
@Getter
public enum DemoStatusEnum implements IEnum<Integer> {
    DEFAULT(0, "default"),
    NORMAL(1, "normal"),
    LOCKED(2, "locked");

    DemoStatusEnum(Integer value, String desc) {
        this.value = value;
        this.desc = desc;
    }

    private Integer value;
    private String desc;

    @Override
    public Integer getValue() {
        return this.value;
    }
}

 如果不想繼承IEnum<T>,可以通過(guò)第二種方式,就是增加一個(gè)注解的方式@EnumValue

    @EnumValue
    private Integer value;
    @JsonValue
    private String desc;

自動(dòng)轉(zhuǎn)換實(shí)現(xiàn):

配置了Enums枚舉,實(shí)體中設(shè)置了枚舉類型,那么mybatis-plus如何轉(zhuǎn)換的呢?重點(diǎn)是看這里

mybatis-plus:
  global-config:
    db-config:
      logic-not-delete-value: 0  #邏輯未刪除值為數(shù)據(jù)庫(kù)主鍵
      logic-delete-value: id #邏輯刪除值是個(gè)d
      # logic-delete-value: "now()" #邏輯刪除值是個(gè)db獲取時(shí)間的函數(shù)
      # logic-not-delete-value: "null"  #邏輯未刪除值為字符串 "null"
      # logic-not-delete-value: "1753-01-01 00:00:00"
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # 如果是放在src/main/java目錄下 classpath:/com/*/*/mapper/*Mapper.xml
    # 如果是放在resource目錄 classpath:/mapper/**.xml
    default-enum-type-handler: org.apache.ibatis.type.EnumOrdinalTypeHandler
    # 如果是放在src/main/java目錄下 classpath:/com/*/*/mapper/*Mapper.xml
    # 如果是放在resource目錄 classpath:/mapper/**.xml
    # 支持統(tǒng)配符 * 或者 ; 分割
    typeEnumsPackage: com.fii.gxback.eam.domain.enums

通過(guò)上述的配置后,就可以了。那么,接下來(lái)我們重點(diǎn)分析一下type-enums-package

按照官方文檔說(shuō)明:

枚舉類 掃描路徑,如果配置了該屬性,會(huì)將路徑下的枚舉類進(jìn)行注入,讓實(shí)體類字段能夠簡(jiǎn)單快捷的使用枚舉屬性

通過(guò)扒源碼發(fā)現(xiàn),其實(shí)是幫我們實(shí)現(xiàn)了對(duì)應(yīng)的 typehandler(com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler)

其中,isMpEnums中,判定整合兩種方式的判定,即 IEnum.class、EnumValue.class

/**
 * 判斷是否為MP枚舉處理
 *
 * @param clazz class
 * @return 是否為MP枚舉處理
 * @since 3.3.1
 */
public static boolean isMpEnums(Class<?> clazz) {
    return clazz != null && clazz.isEnum() && (IEnum.class.isAssignableFrom(clazz) || findEnumValueFieldName(clazz).isPresent());
}

/**
     * 查找標(biāo)記標(biāo)記EnumValue字段
     *
     * @param clazz class
     * @return EnumValue字段
     * @since 3.3.1
     */
public static Optional<String> findEnumValueFieldName(Class<?> clazz) {
    if (clazz != null && clazz.isEnum()) {
        String className = clazz.getName();
        return Optional.ofNullable(CollectionUtils.computeIfAbsent(TABLE_METHOD_OF_ENUM_TYPES, className, key -> {
            Optional<Field> optional = Arrays.stream(clazz.getDeclaredFields())
                // 過(guò)濾包含注解@EnumValue的字段
                .filter(field -> field.isAnnotationPresent(EnumValue.class))
                .findFirst();
            return optional.map(Field::getName).orElse(null);
        }));
    }
    return Optional.empty();
}

然后,在com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean#buildSqlSessionFactory中,

// 取得類型轉(zhuǎn)換注冊(cè)器
TypeHandlerRegistry typeHandlerRegistry = targetConfiguration.getTypeHandlerRegistry();
classes.stream()
    .filter(Class::isEnum)
    .filter(MybatisEnumTypeHandler::isMpEnums)
    .forEach(cls -> typeHandlerRegistry.register(cls, MybatisEnumTypeHandler.class));

驗(yàn)證邏輯

controller:

@RequestMapping("/{id}")
public Demo get(@PathVariable("id") Long id) {
    return demoService.getById(id);
}

輸出:

"status": "DEFAULT"

可以看到,status最終輸出的不是魔術(shù)數(shù)字0,而是枚舉值default。

其實(shí),跟一下代碼,可以發(fā)現(xiàn),跟我們自己手寫一個(gè)typeHandler沒(méi)區(qū)別,這里最終獲取轉(zhuǎn)換值時(shí),調(diào)用了com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler#getNullableResult(java.sql.ResultSet, int),此時(shí)已經(jīng)拿到了枚舉值的具體類是什么了。接下來(lái)就是調(diào)用valueOf去獲取對(duì)應(yīng)的枚舉值即可。

附源碼:

package org.apache.ibatis.type;

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

public class EnumOrdinalTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {
    private final Class<E> type;
    private final E[] enums;

    public EnumOrdinalTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        } else {
            this.type = type;
            this.enums = (Enum[])type.getEnumConstants();
            if (this.enums == null) {
                throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
            }
        }
    }

    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.ordinal());
    }

    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int ordinal = rs.getInt(columnName);
        return ordinal == 0 && rs.wasNull() ? null : this.toOrdinalEnum(ordinal);
    }

    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int ordinal = rs.getInt(columnIndex);
        return ordinal == 0 && rs.wasNull() ? null : this.toOrdinalEnum(ordinal);
    }

    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int ordinal = cs.getInt(columnIndex);
        return ordinal == 0 && cs.wasNull() ? null : this.toOrdinalEnum(ordinal);
    }

    private E toOrdinalEnum(int ordinal) {
        try {
            return this.enums[ordinal];
        } catch (Exception var3) {
            throw new IllegalArgumentException("Cannot convert " + ordinal + " to " + this.type.getSimpleName() + " by ordinal value.", var3);
        }
    }
}

到此這篇關(guān)于mybatis-plus enum實(shí)現(xiàn)枚舉類型自動(dòng)轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)mybatis-plus 枚舉自動(dòng)轉(zhuǎn)換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評(píng)論