Spring boot – Database Column <-> Entity Attribute(Enum)

By | 2022년 8월 12일
Table of Content

Spring boot – Database Column <-> Entity Attribute(Enum)

DB 컬럼을 Enum 으로 변경할 때 AttributeConverter 를 써보자.

공통 메소드 추출

public interface BaseEnum<V> {

    V getValue();

    static <E extends Enum<E> & BaseEnum<ID>, ID> E fromValue(ID value, Class<E> type) {
        if (value == null) {
            return null;
        }

        for (E e : type.getEnumConstants()) {
            if (e.getValue().equals(value)) {
                return e;
            }
        }

        return null;
    }
}

BaseEnumConverter

@Converter
public class BaseEnumConverter<E extends BaseEnum<V>, V> implements AttributeConverter<E, V> {

    @Override
    public V convertToDatabaseColumn(E attribute) {
        return attribute != null ? attribute.getValue() : null;
    }

    @Override
    public E convertToEntityAttribute(V dbData) {
        throw new RuntimeException("override this method.");
    }
}

Enum 생성

public enum YNType implements BaseEnum<String> {

    Y("Y"),
    N("N");

    private final String value;

    YNType(String value) {
        this.value = value;
    }

    @Override
    public String getValue() {
        return value;
    }
}
public enum StatusType implements BaseEnum<Integer> {
    BAD(1),
    GOOD(2),
    UNKNOWN(3);

    private final Integer value;

    StatusType(int value) {
        this.value = value;
    }

    @Override
    public Integer getValue() {
        return value;
    }
}

EnumConverter

public class YNTypeConverter extends BaseEnumConverter<YNType, String> {

    @Override
    public YNType convertToEntityAttribute(String dbData) {
        return BaseEnum.fromValue(dbData, YNType.class);
    }
}
public class StatusTypeConverter extends BaseEnumConverter<StatusType, Integer> {

    @Override
    public StatusType convertToEntityAttribute(Integer dbData) {
        return BaseEnum.fromValue(dbData, StatusType.class);
    }
}

답글 남기기