MybatisPlus自定义枚举映射

1、问题的由来

在平时开发中多多少少肯定会遇到一些例如status...等特殊含义的字段值,虽然传递10:ADMIN,20:NORMAL可以解决业务需求,但是不是很直观

2、使用MP自定义枚举解决

User

package com.ly.plugins.mybatisplus;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;

/**
 * @author : ly
 */
@Accessors(chain = true)
@TableName("user")
@Data
public class User {
    @TableId
    private Integer id;
    private String username;
    private String password;
	// 自定义枚举类型
    private UserType userType;
}

UserType

package com.ly.plugins.mybatisplus;

import com.baomidou.mybatisplus.annotation.IEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * @author : ly
 */
@Getter
@AllArgsConstructor
public enum UserType implements IEnum<Integer> {

    ADMIN(1, "admin"),
    NORMAL(2, "normal");

    private Integer code;

    private String val;

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

测试

package com.ly.plugins;

import com.ly.plugins.mybatisplus.User;
import com.ly.plugins.mybatisplus.UserMapper;
import com.ly.plugins.mybatisplus.UserType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author : ly
 */
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test01(){
        User user = new User().setId(2).setUsername("lisi").setPassword("321").setUserType(UserType.NORMAL);
        userMapper.insert(user);
    }

    @Test
    public void test02(){
        User user = userMapper.selectById(1);
        System.out.println("user = " + user);
    }
}

结果
image

posted @   我也有梦想呀  阅读(207)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2022-07-24 使用Redis实现一个分布式的全局ID
点击右上角即可分享
微信分享提示