프로젝트/자프링 -> 코프링 마이그레이션

Kotlin 각종 어노테이션 사용법(@Index, @Embeddable, @Size)

Junuuu 2022. 12. 1. 00:01
반응형

 

@Embeddable을 data class에 붙여주자 다음과 같은 경고가 발생하였습니다.

For property-based access both setter and getter should be present

 

이대로 실행은 되나 경고가 불편하기 때문에 해결하고자 합니다.

 

JPA가 FIELD, 프로퍼티(getter, setter) 액세스 두 가지 방법을 사용합니다.

프로퍼티 접근은 최근에는 권장되지 않으며 getter가 존재하여 JPA가 정확히 판단하기 어려워서 나오는 경고 메시지입니다.

 

@Column으로 필드 접근 방식을 사용하고 있다는 것을 명시하면 해결됩니다.

@Embeddable
data class Address(
    @Column val zipCode : String,
    val streetNameAddress : String,
    val detailAddress : String,
)

 

@Index를 Kotlin에 적용하자 컴파일 에러가 발생하였습니다.

@Table(
        name = "member"
        , indexes = {
        @Index(name = "unique_idx_user_id", columnList = "user_id", unique = true),
        @Index(name = "unique_idx_nickname", columnList = "nickname", unique = true),
        @Index(name = "unique_idx_phone_number", columnList = "phone_number", unique = true)
}
)

 

An annotation can't be used as the annotations argument

해당 어노테이션을 주석인자로 사용할 수 없다는 에러가 발생합니다.

 

중괄호를 대괄호로 변경하고 @를 제외해주면 정상적으로 컴파일됩니다.

@Table(
    name = "member", indexes = [
        Index(name = "unique_idx_user_id", columnList = "user_id", unique = true),
        Index(name = "unique_idx_nickname", columnList = "nickname", unique = true),
        Index(name = "unique_idx_phone_number", columnList = "phone_number", unique = true)
    ]
)

 

유효성 검사를 위한 @Valid, @Size 동작하지 않음

@NotBlank(message = "아이디를 입력해주세요.")
@Size(min = 5, max = 20, message = "아이디는 5자 이상 20자 이하로 입력해주세요.")
val userId: String,

 

테스트에서 RequestDTO에 제약사항을 정의하였으나 400 상태 코드를 반환하지 않고 201 상태 코드를 반환했습니다.

 

결론부터 이야기하기하면 다음과 같이 하면 해결됩니다.

@field:NotBlank(message = "아이디를 입력해주세요.")
@field:Size(min = 5, max = 20, message = "아이디는 5자 이상 20자 이하로 입력해주세요.")
val userId: String,

 

이유는 간단합니다.

 

필드가 아닌 생성자에서 @NotBlank, @Size를 선언하기 때문에 Java로 컴파일되었을 때 생성자에 어노테이션이 생깁니다.

 

 

 

참고 자료

https://www.inflearn.com/questions/78106

 

@Embeddable 사용시 질문 입니다. - 인프런 | 질문 & 답변

안녕하세요 강사님 @Embeddable 어노테이션 관련 부분을 실습 하고 있는데요 @Getter@Setter@Embeddablepublic class Ex18Period {// @Column(name = 'STARTDATE') private LocalDateTi...

www.inflearn.com

https://stackoverflow.com/questions/70974295/index-annotation-leads-to-this-annotation-is-not-applicable-to-target-member

 

@Index annotation leads to "This annotation is not applicable to target 'member property with backing field'"

I am trying to create an index on a foreign key using the @Index annotation. Unfortunately, the compiler complains with the following message: This annotation is not applicable to target 'member pr...

stackoverflow.com

https://velog.io/@lsb156/SpringBoot-Kotlin%EC%97%90%EC%84%9C-Valid%EA%B0%80-%EB%8F%99%EC%9E%91%ED%95%98%EC%A7%80-%EC%95%8A%EB%8A%94-%EC%9B%90%EC%9D%B8JSR-303-JSR-380

 

SpringBoot - Kotlin에서 @Valid가 동작하지 않는 원인(JSR-303, JSR-380)

Spring을 사용하다보면 Controller에서 매우 자주 사용되는 Annotation인 @Valid가 있을건데 이상하게 코틀린에서 사용하다보면 동작하지 않는것을 확인할 수 있다. 여기서 이에대한 해결방법이나 원리

velog.io