首先创建一个接口
public interface ConvertTest {
Integer getValue();
}
创建对应枚举类
@RequiredArgsConstructor//为final字段创建构造函数
public enum Process implements ConvertTest {
草稿状态(1),
审批中(2),
审批通过(3),
驳回(4);
@Getter
private final Integer value;
public static Converter converter = new Converter();
public static class Converter extends TestAttributeConverter<Process> {
public Converter() {
super(values());
}
}
}
public abstract class TestAttributeConverter<T extends ConvertTest> implements AttributeConverter<T, Integer> {
final T[] values;
public TestAttributeConverter(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);
}
}
创建测试类
public class ConverterTest {
@Test
public void test() {
Process process = Process.converter.convertToEntityAttribute(1);//可直接根据值来获取枚举类型
System.out.println(process);
Assert.assertNotNull(process);
}
}