欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单的使用枚举类

程序员文章站 2022-06-16 16:58:36
...

枚举类使用例子:

public enum SystemUserType {
                            PORTAL("业务用户"),

                            ADMIN("后台管理用户");

    private String label;

    private SystemUserType(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }

    public static SystemUserType getEnum(String name) {
        if (name == null) {
            return null;
        }

        for (SystemUserType enums : values()) {
            if (enums.name().equals(name)) {
                return enums;
            }
        }
        return null;
    }

    /**
     * 如果没有对应的枚举则抛出异常
     * 
     * @param name
     * @return
     */
    public static SystemUserType checkEnum(String name) throws BusinessException {
        SystemUserType enums = getEnum(name);
        if (enums == null) {
            throw new BusinessException("系统用户类型不正确");
        }
        return enums;
    }
}

简单的使用枚举类

Hibernate注解之@Enumerated

/** 枚举:账号**状态枚举
     *  账户状态,1-未**   2-**
     *  */
    public enum State {
        inactive(1, "未**"),
        Activated(2, "已**");
        /** 值 */
        private int value;
        private String label;
 
        /** 取值 */
        public String getLabel() { return label; }
        public int getValue() { return this.value; }
 
        State(int value, String name) {
            this.value = value;
            this.label = name;
        }
    }
    @Column(nullable = false, length = 6)
    @Enumerated(EnumType.STRING)
    private SystemUserType userType;
 @Enumerated默认的value是ordinal,取的就是枚举的下标,下标就是 1, 2

此时数据库的数据类型需要是数值类型

    @Enumerated(value=EnumType.STRING),取的就是枚举的名字,名字就是 未** , 已**

此时数据库的数据类型需要是varchar那些字符串类型

参考的博客:https://blog.csdn.net/weixin_41888813/article/details/81509687

相关标签: 枚举类 java