1. Enum Interface
import com.fasterxml.jackson.annotation.JsonValue;
public interface SampleEnum {
@JsonValue
String getCode();
}
다음과 같은 SampleEnum 이라는 인터페이스를 작성한다
2. Enum Class
import java.util.Arrays;
import java.util.NoSuchElementException;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public enum SampleType implements SampleEnum {
SAMPLE_ONE("sample1"),
SAMPLE_TWO("sample2");
private final String code;
public static SampleType fromCode(String code) {
return Arrays.stream(SampleType.values())
.filter(type -> type.getCode().equals(code))
.findAny()
.orElseThrow(() -> new NoSuchElementException("Wrong code"));
}
}
SampleEnum 인터페이스를 상속받은 Enum 클래스 SampleType을 작성한다
3. AttributeConverter
import java.util.EnumSet;
import java.util.NoSuchElementException;
import javax.persistence.AttributeConverter;
public class SampleCodeConverter<E extends Enum<E> & SampleEnum> implements AttributeConverter<E, String> {
private Class<E> eClass;
protected SampleCodeConverter(Class<E> eClass) {
this.eClass = eClass;
}
@Override
public String convertToDatabaseColumn(E attribute) {
return attribute.getCode();
}
@Override
public E convertToEntityAttribute(String dbData) {
return EnumSet.allOf(eClass).stream()
.filter(e -> e.getCode().equals(dbData))
.findAny()
.orElseThrow(() -> new NoSuchElementException("Wrong Code"));
}
}
SampleEnum 인터페이스에 대한 AttributeConverter를 구현한다
4. Enum Class AttributeConverter
import javax.persistence.converter
@Converter
public class SampleTypeConverter extends SampleCodeConverter<SampleType> {
SampleTypeConverter() {
super(SampleType.class);
}
}
5. JPA 사용
import javax.persistence.Entity;
@Entity
public class SampleEntity {
@Id
private Long id;
@Convert(converter=SampleTypeConverter.class)
private SampleType sampleType;
// 생략
}
'SpringBoot > JPA' 카테고리의 다른 글
[JDBC] JPA(Read) + jdbcTemplate(Write) 사용하기 (0) | 2022.04.14 |
---|