[JPA] Converter
Converter
* db값과 객체에 넣을 값이 다르다면 컨버터를 사용한다.
* 엔티티의 속성 중에 연관관계가 없는 클래스 타입이 있다면, 이걸 convert해야 db에 잘 넣을 수 있고 반대로 db에서 값을 읽어와서 객체로 넣어줄 수 있다.
* 속성으로 넣을 클래스 만들기(db값과 객체의 값 두개 다 속성으로 가지는 클래스) -> converter 클래스만들어서 값 convert하기
*컨버터 클래스는 AttributeConverter 인터페이스를 구현한다 AttributeConverter<객체타입, 필드타입> => 여기서 필드타입은 대문자(ex. Integer)로 써줘야함
* 속성위에 @Convert로 해서 컨버터를 지정 => 컨버터에서 속성을 autoApply=true를 하면 해당 타입을 속성들을 자동으로 변환해줌. 따라서 @Convert <<이건 안해줘도 됨.
ㄴ autoApply는 내가 구현한 클래스에서만 사용하기. integer나 String같은 컨버터에 하면 모든 Integer, String 타입들이 다 컨버트됨.
* 필요하든 안하든 todb, toobject 다 구현하기!!
- Book
@Convert(converter = BookAndStatusConverter.class)
private BookStatus status;
-BookAndStatusConverter
@Converter
public class BookAndStatusConverter implements AttributeConverter<BookStatus, Integer> {
@Override
public Integer convertToDatabaseColumn(BookStatus attribute) {
return attribute.getCode();
}
@Override
public BookStatus convertToEntityAttribute(Integer dbData) {
return dbData!=null ? new BookStatus(dbData) : null;
}