@Convert
🔁 @Convert
정의
@Convert는 JPA 엔티티의 필드 값과 데이터베이스 컬럼 값 사이의 변환 규칙을 지정하는 애너테이션이다.
엔티티에 저장되는 값과 DB에 저장되는 값의 타입이나 형식이 다를 때 유용하다.
🧩 Artifact
javax.persistence
🛠 역할
- 엔티티 필드를 DB 컬럼에 저장할 때 변환한다.
- DB 값을 다시 엔티티 속성으로 읽을 때 변환한다.
AttributeConverter와 함께 사용한다.
🧪 사용법
Global 설정
@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, LocalDateTime> {
@Override
public LocalDateTime convertToDatabaseColumn(LocalDate localDate) {
return localDate != null ? localDate.atStartOfDay() : null;
}
@Override
public LocalDate convertToEntityAttribute(LocalDateTime localDateTime) {
return localDateTime != null ? localDateTime.toLocalDate() : null;
}
}
| 속성 | 기능 |
|---|---|
autoApply |
대상 타입에 대해 @Convert를 따로 쓰지 않아도 자동 적용할지 여부를 지정한다. |
필드 설정
@Entity
@Data
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_seq", length = 20, nullable = false)
private Integer userSeq;
@Column(name = "regist_time", nullable = false)
@Convert(converter = LocalDateAttributeConverter.class)
private LocalDate registTime;
@Column(name = "last_login_time")
@Convert(converter = LocalDateAttributeConverter.class)
private LocalDate lastLoginTime;
}
엔티티 레벨 설정
@Entity
@Data
@Table(name = "user")
public class User {
@Convert(converter = LocalDateAttributeConverter.class, attributeName = "registTime")
@Convert(converter = LocalDateAttributeConverter.class, attributeName = "lastLoginTime")
...
}
⚠️ 주의사항
caution
@Convert는@Id에는 적용할 수 없다.
- 변환 대상 타입과
AttributeConverter제네릭 타입이 맞아야 한다. - 자동 적용(
autoApply)을 쓰면 예상치 못한 필드에도 적용될 수 있으므로 주의한다. - 필드별로 명시적으로 지정하면 의도가 더 분명해진다.
📌 정리
@Convert는 엔티티 값과 DB 값의 변환 규칙을 지정하는 애너테이션이다.AttributeConverter와 함께 사용한다.- 필드별 적용과 자동 적용을 상황에 맞게 선택하는 것이 중요하다.
댓글남기기