枚举
枚举是一个被命名的整型常数的集合,用于声明一组带标识符的常数。枚举在曰常生活中很常见,例如一个人的性别只能是“男”或者“女”,一周的星期只能是 7 天中的一个等。类似这种当一个变量有几种固定可能的取值时,就可以将它定义为枚举类型。
项目案例(直接上代码,做记录参考)
目录结构截图
BaseEnum 枚举基类接口
package com.example.demo.enums.base;
public interface BaseEnum {
/**
* 根据枚举值和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;
}
}
实体类
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对象", 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("学历(0小学,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("手机号")
@TableField("phone")
private String phone;
@ApiModelProperty("地址")
@TableField("address")
private String address;
@ApiModelProperty("备注")
@TableField("memo")
private String memo;
}
注意实体类里的性别字段 ,案例中"学历"也是个枚举.
序列化BaseEnum接口
序列化相关代码
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());
}
}
反序列化相关代码
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() + "实体类中找不到" + 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);
}
}
加载相关序列化到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 构建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枚举转换 并加载到bean中
package com.example.demo.enums.base;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
/**
* 表单BaseEnum枚举转换
*/
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());
}
}
测试案例
数据库中存的数据
查询返回前台的数据
新增数据(传code 一般都是下拉框传到后台一般也是code 值)
后台接收到的实体类数据
保存到数据后的数据
文章来源:https://www.toymoban.com/news/detail-757942.html
结束语:
1.没有mybatis_plus 通用枚举处理,有大佬给个mybatis_plus的案例不?最好包含前后端的显示以及传值情况的.文章来源地址https://www.toymoban.com/news/detail-757942.html
到了这里,关于(四)springboot 数据枚举类型的处理(从前端到后台数据库)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!