본문 바로가기
Spring Boot

[Spring] 2개 이상의 유니크 키를 분리하여 예외처리 하기

by palbokdev 2023. 1. 31.
@Entity
@Table(uniqueConstraints = {
  @UniqueConstraint(name = "UC_email", columnNames = { "email" } ),
  @UniqueConstraint(name = "UC_username", columnNames = { "userName" } )
})
public User myFancyServiceMethod(...) {
  try {
    // do your stuff here
    return userRepository.save( user );
  }
  catch( ConstraintViolationException e ) { 
    if ( isExceptionUniqueConstraintFor( "UC_email" ) ) {
      throw new EmailAddressAlreadyExistsException();
    }
    else if ( isExceptionUniqueConstraintFor( "UC_username" ) ) {
      throw new UserNameAlreadyExistsException();
    }
  }
}

 

email과 username 필드 모두 유니크 키라고 가정하였을때,

중복된 값이 들어오는 경우 분리하여 예외처리 해줘야 하는 경우가 존재합니다.

 

email이 제약사항을 위반한경우 email 관련 코드

username이 제약사항을 위반한경우 username 관련 코드

 

엔티티 클래스에서 UniqueConstraint 이름을 미리 정의하고

exception이 발생하였을때 해당 제약사항의 이름을 통해 분류하면 됩니다.

 

출처 : https://stackoverflow.com/questions/42462829/identify-constraint-name-that-trigger-dataintegrityviolationexception