优雅地实现java枚举与int值地转换(JPA)

使用

import lombok.Data;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor//为final字段创建构造函数
public enum Process implements ConvertibleEnum {
    CREATED(1000)//已创建,未提交
    , POSTED(1100)//已提交,未被查看
    , REVIEWED(1200)//已被查看
    ;

    @Getter
    private final Integer value;
    public static Converter converter = new Converter();

    public static class Converter extends EnumAttributeConverter<Process> {
        public Converter() {
            super(values());
        }
    }
}

测试:

import org.junit.Assert;
import org.junit.Test;

public class EnumConverterTest {
    @Test
    public void test() {
        Process process = Process.converter.convertToEntityAttribute(1000);//可直接根据值来获取枚举类型
        System.out.println(process);//输出CREATED
        Assert.assertNotNull(process);
    }
}

相关实现:

public interface ConvertibleEnum {
    Integer getValue();
}
import javax.persistence.AttributeConverter;

public abstract class EnumAttributeConverter<T extends ConvertibleEnum> implements AttributeConverter<T, Integer> {
    final T[] values;

    public EnumAttributeConverter(T[] values) {
        this.values = values;
    }

    @Override
    public Integer convertToDatabaseColumn(T attribute) {
        return attribute.getValue();
    }

    @Override
    public T convertToEntityAttribute(Integer dbData) {
        for (T value : values) {
            if (value.getValue().equals(dbData))
                return value;
        }
        return null;
    }

    public T convertToEntityAttributeHard(Integer dbData) {
        T t = convertToEntityAttribute(dbData);
        if (t != null)
            return t;
        else throw new IllegalArgumentException("不存在指定枚举" + dbData);
    }
}
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页