duplicateKeyException
Environment
Language: Java
DB: MySQL
오류
Caused by: java.lang.IllegalStateException: Duplicate key 400 BAD_REQUEST (attempted merging values DUPLICATED_EMAIL and NOT_EQUAL_PASSWORD)
at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:135)
at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:182)
원인
DUPLICATED_EMAIL(HttpStatus.BAD_REQUEST, "이미 존재하는 이메일 입니다."),
NOT_EQUAL_PASSWORD(HttpStatus.BAD_REQUEST,"입력한 비밀번호가 상이합니다."),
// HttpStatus -> ErrorCode 조회
private static final Map<HttpStatus, ErrorCode> BY_HTTPSTATUS =
Stream.of(values()).collect(Collectors.toMap(ErrorCode::getHttpStatus, e -> e));
public static Optional<ErrorCode> valueOfHttpStatus(HttpStatus httpStatus){
return Optional.ofNullable(BY_HTTPSTATUS.get(httpStatus));
}
- toMap()
- If the mapped keys contain duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys might have duplicates, use toMap(Function, Function, BinaryOperator) instead.
- HttpStatus로부터 Enum을 조회하려고 할 때, Map을 활용하는데 이 때 key 값(= HttpStatus)이 중복될 경우, duplicate관련 IllegalStateException이 발생할 수 있음
해결
// HttpStatus -> ErrorCode 조회
private static final Map<HttpStatus, ErrorCode> BY_HTTPSTATUS =
Stream.of(values()).collect(Collectors.toMap(ErrorCode::getHttpStatus, e -> e, ((e1, e2) -> e1)));
// Stream.of(values()).collect(Collectors.toMap(ErrorCode::getHttpStatus, e -> e, ((e1, e2) -> e2)));
public static Optional<ErrorCode> valueOfHttpStatus(HttpStatus httpStatus){
return Optional.ofNullable(BY_HTTPSTATUS.get(httpStatus));
}
- toMap(Function, Function, BinaryOperator)
- BinaryOperator에서 먼저 put할 데이터를 사용할지 나중에 put한 데이터를 사용할지 추가
📚 참고 자료
'Java > JPA with Error' 카테고리의 다른 글
[해결방법] EmptyResultDataAccessException (0) | 2024.08.11 |
---|---|
[해결방법] JdbcTypeRecommendationException (0) | 2023.12.25 |
[해결방법] BeanCreationException (0) | 2023.12.25 |
[해결 방법] org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl ... is closed (1) | 2023.10.08 |
[해결 방법] org.hibernate.QueryException (0) | 2023.09.26 |