(四)springboot 数据枚举类型的处理(从前端到后台数据库)

枚举

枚举是一个被命名的整型常数的集合,用于声明一组带标识符的常数。枚举在曰常生活中很常见,例如一个人的性别只能是“男”或者“女”,一周的星期只能是 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 值)

在这里插入图片描述

后台接收到的实体类数据

在这里插入图片描述

保存到数据后的数据

在这里插入图片描述

结束语:
1.没有mybatis_plus 通用枚举处理,有大佬给个mybatis_plus的案例不?最好包含前后端的显示以及传值情况的.

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将前端页面数据插入到数据库中,你需要进行以下步骤: 1. 创建一个实体类,用于存储前端页面传来的数据,并在该实体类上使用 `@Entity` 注解,表示该类对应数据库中的一张表。 2. 使用 `@Repository` 注解或者继承 `JpaRepository` 接口,创建一个数据访问层的类,用于与数据库进行交互。 3. 在控制器层中,使用 `@Autowired` 注解将数据访问层的类注入到控制器中,并在处理前端页面数据的方法中调用数据访问层的方法,将数据插入到数据库中。 以下是一个示例代码: 实体类: ```java @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // 省略getter和setter方法 } ``` 数据访问层: ```java @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 控制器: ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepository userRepository; @PostMapping("/") public User createUser(@RequestBody User user) { return userRepository.save(user); } } ``` 在上面的代码中,`@PostMapping` 注解表示该方法处理 HTTP POST 请求,并将前端页面传来的数据作为 `User` 对象的参数。`@RequestBody` 注解表示将请求体中的数据绑定到该参数上。 `userRepository.save(user)` 方法将 `User` 对象保存到数据库中,并返回保存后的 `User` 对象。该对象包含了数据库自动生成的 ID 值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值