AttributeConverter 는 JPA(Java Persistence API)에서 엔티티의 필드 값을 DB 컬럼과 매핑할 때 변환하는 역할을 하는 인터페이스
자바 객체의 특정 필드 값을 데이터베이스 저장 형식에 맞게 변환하거나, DB 값을 다시 자바 객체 형식으로 변환할 때 사용
int, long, String, LocalDate와 같은 타입은 DB 테이블의 한 개 칼럼에 매핑된다. 이와 비슷하게 밸류 타입의 프로퍼티를 한 개 칼럼에 매핑해야 할 때도 있다.
예를 들어 Length가 길이 값과 단위의 두 프로퍼티를 갖고 있는데 DB 테이블에는 한 개의 칼럼에 '1000mm' 와 같은 형식으로 저장하고싶을때 -> AttributeConverter 을 사용하면 이를 해결할 수 있다.
public class Length {
private int value; ----> WIDTH VARCHAR(20) {1000mm 로 저장}
private String unit;
}
public interface AttributeConverter<X,Y> {
public Y convertToDatabaseColumn (X attribute);
public X convertToEntityAttribute (Y dbData);
}
타입파라미터 X는 벨류 타입이고 Y 는 DB 타입이다 convertToDatabaseColumn() 메서드는 밸류 타입을 DB 칼럼 값으로 변환하는 기능을 구현하고 convertToEntityAttribute() 메서드는 DB 칼럼 값을 밸류로 변환하는 기능을 구현한다.
아래는 예시를 위한 Money를 위한 AttributeConverter을 구현이다.
@Converter(autoApply = true) // true로 설정하면 모델에 출현하는 모든 Money 타입의 프로퍼티에 대해 MoneyConverter를 자동으로 적용
public class MoneyConverter implements AttributeConverter<Money,Integer> {
@Override
public Integer convertToDatabaseColumn (Money money) {
return money == null ? null : money.getValue();
}
@Override
public Integer convertToEntityAttribute (Integer value) {
return money == null ? null : new Money(value);
}
}
@Entity
@Table(name = "purchase_order")
public class Order {
...
@Column(name = "total_amounts")
private Money totalAmounts; // MoneyConverter를 적용해 값 변환됨
}
public class Order {
@Column(name = "totla_amounts")
@Converter(converter = MoneyConverter.class)
private Money totalAmounts;