国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

(四)springboot 數(shù)據(jù)枚舉類型的處理(從前端到后臺(tái)數(shù)據(jù)庫(kù))

這篇具有很好參考價(jià)值的文章主要介紹了(四)springboot 數(shù)據(jù)枚舉類型的處理(從前端到后臺(tái)數(shù)據(jù)庫(kù))。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

枚舉

枚舉是一個(gè)被命名的整型常數(shù)的集合,用于聲明一組帶標(biāo)識(shí)符的常數(shù)。枚舉在曰常生活中很常見(jiàn),例如一個(gè)人的性別只能是“男”或者“女”,一周的星期只能是 7 天中的一個(gè)等。類似這種當(dāng)一個(gè)變量有幾種固定可能的取值時(shí),就可以將它定義為枚舉類型。

項(xiàng)目案例(直接上代碼,做記錄參考)

目錄結(jié)構(gòu)截圖

springboot 枚舉類型處理,spring boot,前端,數(shù)據(jù)庫(kù)

BaseEnum 枚舉基類接口

package com.example.demo.enums.base;

public interface BaseEnum {
    /**
     * 根據(jù)枚舉值和type獲取枚舉
     */
    public static <T extends BaseEnum> T getEnum(Class<T> type, int code) {
        T[] objs = type.getEnumConstants();
        for (T em : objs) {
            if (em.getCode().equals(code)) {
                return em;
            }
        }
        return null;
    }


    /**
     * 獲取枚舉值
     *
     * @return
     */
    Integer getCode();

    /**
     * 獲取枚舉文本
     *
     * @return
     */
    String getLabel();
}

自定義枚舉(以性別為例(女,男,保密))

package com.example.demo.enums;

import com.example.demo.enums.base.BaseEnum;

public enum SexEnumType implements BaseEnum {
    WOMEN(0, "女"), MEN(1, "男"), ENCRY(2, "保密");

    private Integer code;//枚舉值

    private String leble;//枚舉文本

    SexEnumType(Integer code, String leble) {
        this.code = code;
        this.leble = leble;
    }


    @Override
    public Integer getCode() {
        return code;
    }

    @Override
    public String getLabel() {
        return leble;
    }
}

實(shí)體類

package com.example.demo.model.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.example.demo.enums.EducationType;
import com.example.demo.enums.SexEnumType;
import com.example.demo.model.baseModel.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

/**
 * <p>
 * 
 * </p>
 *
 * @author gaozhen
 * @since 2022-12-03
 */
@Getter
@Setter
@TableName("eprk_sm_user")
@ApiModel(value = "SmUser對(duì)象", description = "")
public class SmUser extends BaseEntity {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty("用戶名稱")
    @TableField("user_name")
    private String userName;

    @ApiModelProperty("用戶編碼")
    @TableField("user_code")
    private String userCode;

    @ApiModelProperty("用戶登錄密碼")
    @TableField("user_password")
    private String userPassword;

    @ApiModelProperty("年齡")
    @TableField("age")
    private Integer age;

    @ApiModelProperty("學(xué)歷(0小學(xué),1初中,2高中,3大專,4本科,5研究生,6保密)")
    @TableField("education")
    private EducationType education;

    @ApiModelProperty("性別(0:女,1:男,2:保密)")
    @TableField("sex")
    private SexEnumType sex;

    @ApiModelProperty("郵箱地址")
    @TableField("email")
    private String email;

    @ApiModelProperty("手機(jī)號(hào)")
    @TableField("phone")
    private String phone;

    @ApiModelProperty("地址")
    @TableField("address")
    private String address;

    @ApiModelProperty("備注")
    @TableField("memo")
    private String memo;


}

注意實(shí)體類里的性別字段 ,案例中"學(xué)歷"也是個(gè)枚舉.

序列化BaseEnum接口

序列化相關(guān)代碼

package com.example.demo.enums.base;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * BaseEnum 序列化
 */
public class BaseEnumSerializer extends JsonSerializer<BaseEnum> {
    @Override
    public void serialize(BaseEnum value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeNumber(value.getCode());
        gen.writeStringField(gen.getOutputContext().getCurrentName() + "Text", value.getLabel());
    }
}

反序列化相關(guān)代碼

package com.example.demo.enums.base;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.io.IOException;

/**
 * BaseEnum反序列化
 */
@Slf4j
public class BaseEnumDeserializer extends JsonDeserializer<Enum> {


    @Override
    public Enum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonNode node = p.getCodec().readTree(p);
        String currentName = p.currentName();
        Object currentValue = p.getCurrentValue();
        Class findPropertyType = null;
        findPropertyType = BeanUtils.findPropertyType(currentName, currentValue.getClass());
        if (findPropertyType == null) {
            log.info("在" + currentValue.getClass() + "實(shí)體類中找不到" + currentName + "字段");
            return null;
            
        }
        String asText = null;
        asText = node.asText();
        if (StringUtils.isBlank(asText) || (StringUtils.isNotBlank(asText) && asText.equals("0"))) {
            return null;
        }

        if (BaseEnum.class.isAssignableFrom(findPropertyType)) {
            BaseEnum valueOf = null;
            if (StringUtils.isNotBlank(asText)) {
                valueOf = BaseEnum.getEnum(findPropertyType, Integer.parseInt(asText));
            }
            if (valueOf != null) {
                return (Enum) valueOf;
            }

        }

        return Enum.valueOf(findPropertyType, asText);
    }

}

加載相關(guān)序列化到bean

package com.example.demo.enums.base;

import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.TimeZone;

/**
 * 加載baseEnum 構(gòu)建bean定義,初始化Spring容器。
 */
@Configuration
public class EnumBeanConfig {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() {
        BaseEnumSerializer baseEnumSerializer = new BaseEnumSerializer();
        BaseEnumDeserializer baseEnumDeserializer = new BaseEnumDeserializer();
        return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault()).
                serializerByType(BaseEnum.class, baseEnumSerializer).
                deserializerByType(Enum.class, baseEnumDeserializer);
    }
}

表單BaseEnum枚舉轉(zhuǎn)換 并加載到bean中

package com.example.demo.enums.base;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * 表單BaseEnum枚舉轉(zhuǎn)換
 */
public class BaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {


    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new BaseEnumConverter(targetType);
    }

    public class BaseEnumConverter<String, T extends BaseEnum> implements Converter<String, BaseEnum> {

        private Class<T> type;

        public BaseEnumConverter(Class<T> type) {
            this.type = type;
        }

        @Override
        public BaseEnum convert(String source) {
            return BaseEnum.getEnum(type, Integer.parseInt((java.lang.String) source));
        }
    }
}

加載到bean

package com.example.demo.enums.base;

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfigImpl implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new BaseEnumConverterFactory());
    }

}

測(cè)試案例

數(shù)據(jù)庫(kù)中存的數(shù)據(jù)

springboot 枚舉類型處理,spring boot,前端,數(shù)據(jù)庫(kù)

查詢返回前臺(tái)的數(shù)據(jù)

springboot 枚舉類型處理,spring boot,前端,數(shù)據(jù)庫(kù)

新增數(shù)據(jù)(傳code 一般都是下拉框傳到后臺(tái)一般也是code 值)

springboot 枚舉類型處理,spring boot,前端,數(shù)據(jù)庫(kù)

后臺(tái)接收到的實(shí)體類數(shù)據(jù)

springboot 枚舉類型處理,spring boot,前端,數(shù)據(jù)庫(kù)

保存到數(shù)據(jù)后的數(shù)據(jù)

springboot 枚舉類型處理,spring boot,前端,數(shù)據(jù)庫(kù)

結(jié)束語(yǔ):
1.沒(méi)有mybatis_plus 通用枚舉處理,有大佬給個(gè)mybatis_plus的案例不?最好包含前后端的顯示以及傳值情況的.文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-757942.html

到了這里,關(guān)于(四)springboot 數(shù)據(jù)枚舉類型的處理(從前端到后臺(tái)數(shù)據(jù)庫(kù))的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包