@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이 발생하였을때 해당 제약사항의 이름을 통해 분류하면 됩니다.
'Spring Boot' 카테고리의 다른 글
[Spring] IntelliJ RMI TCP Connection 에러 (0) | 2023.03.14 |
---|---|
[Spring] 유니크 키 제약사항을 위반한 경우 HTTP 상태 코드 (0) | 2023.02.01 |
[Spring] @Transactional 롤백 기능 이용하기 (0) | 2023.01.18 |
[JPA] @Entity @Table 차이점 (0) | 2022.09.14 |
[Spring] RestTemplate vs WebClient (0) | 2022.07.27 |