TIL 2024-08-12 VO와 JPA를 쓰면서 컨버터에 대한 깨달음
AttributeConverter
DB와 언어 사이에서 컨버터 역할을 해준다.
예를 들어 객체가 있다고 하자
public class VO {
String value;
}
public class Entity {
private VO name;
}
// 머 그냥 대충 적었다~~
이렇게 있을 때 Entity를 DB에 저장하려고 하면
VO는 원시 타입이거나 지원하지 않는 객체이므로 에러가 뜰것이다.
그래서 컨버터를 사용해서 VO를 db와 맞게 바꿀 수 있다.
@Converter(autoApply = true)
public class VOConverter implements AttributeConverter<VO, String> {
@Override
public String convertToDatabaseColumn(VO vo) {
if (vo == null) {
return null;
}
return vo.value();
}
@Override
public MemberUsername convertToEntityAttribute(String dbData) {
if (daData == null) {
return null;
}
return new VO(dbData);
}
}
JPA(feat. Hibernate) 에서 매개변수로 넣은 값들은 AttributeConverter가 작동하지 않는다.
AttributeConverter 는 다음과 같이 행동한다.
1. DB 데이터를 불러올 때 객체와 매핑
2. 객체를 DB 에 저장할 때 매핑
그러니까 매개변수에서 작동하지 않는다.
Argument [username] of type [java.lang.String] did not match parameter type ~~
막 이런 오류가 뜬다.
아니 나는
boolean existsByUsername(String username);
이렇게 쓰고 싶은데
boolean existsByUsername(VO username);
이렇게 쓰라고 강요한다.
당연히 될 줄 알았지.. 컨버터가 있는데..ㅠ
해결 방법 2가지
1. VO를 매개변수로 준다.
boolean existsByUsername(VO username);
난 이 방법이 싫다.
하면
2. Value 를 명시적으로 붙여준다
boolean existsByUsernameValue(String username);
// directive "existsBy" field "VO.value"
이렇게 명시적으로 필드값을 넣어주면 JPA 에서 SpringData SQL 을 만들 때 자동으로 Value 값을 찾아서 해당 타입에 맞게끔 매개변수를 넣을 수 있게 해준다.
References
https://www.baeldung.com/jpa-attribute-converters
Hibernate ORM 5.4.33.Final User Guide
Fetching, essentially, is the process of grabbing data from the database and making it available to the application. Tuning how an application does fetching is one of the biggest factors in determining how an application will perform. Fetching too much dat
docs.jboss.org
스프링 JPA @Embedded 및 @EmbeddedId
1. 개요 이 예제에서는 복합 키 기반 JPA 엔터티를 쿼리하기 위한 @EmbeddedId 어노테이션 및 " findBy " 메서드의 사용을 다룰 것입니다. 따라서 @EmbeddeId 및 @Embeddable 어노테이션을 사용 하여 JPA 엔터티
recordsoflife.tistory.com