문제상황
UserController
@GetMapping("/check-account-duplicate")
public ResponseEntity<ApiResponse>checkAccountDuplicate(@RequestParam @Valid String account) throws IllegalAccessException {
userService.checkAccountDuplicate(account);
return ResponseEntity.ok(new ApiResponse("사용 가능한 계정입니다."));
}
UserService
public void checkAccountDuplicate(String account) {
Boolean isExist = userRepository.findByUserAccount(account);
if(isExist){
throw new IllegalAccessException("중복된 ID 입니다. 새로운 ID를 입력해주세요");
}
}
UserRepository
public interface UserRepository extends JpaRepository <User,Long> {
User findByUserUUID(UUID uuid);
Boolean findByUserAccount(String account);
}
postman
아이디 중복 검사 로직
- 아이디를 param으로 받아서 userRepository(회원 데이터 저장소)에서 해당 아이디가 존재하는지 확인한다.
- 아이디가 존재하는 경우 중복된 아이디 처리를 해준다.
포스트맨 요청 방법
- @requestParam 으로 요청시에는 url로 전달된 값을 가져오기 때문에 주소 입력란에 직접 작성한다.
- 또는 밑에 Params 칸에서 key-value 로 직접 값을 설정해주면 된다.
원인 분석
The mismatch is happening because the method findByUserAccount in UserRepository is incorrectly defined to return a Boolean when it should actually be returning a User or checking for the existence in a boolean method.
Method Definition Issue
: The method findByUserAccount is expected to return a Boolean, but it is actually returning a User.
userRepository에서 account가 존재하는지 안하는지를 찾을때 리턴값을 boolean으로 설정했다.
하지만 메서드의 이름이 findByUserAccount 였기 때문에 jpa 메서드 이름 규칙에 따라 (boolean값을 return 하는 것이 아닌)
user을 리턴했던것이다. 그래서 userRepositroy 에서 타입이 불일치 한다는 오류가 발생했던것이다.
내가 원하는대로 boolean값을 리턴하도록 하고싶다면 existsBy ~ 를 사용했어야한다.
해결방법
public interface UserRepository extends JpaRepository <User,Long> {
User findByUserUUID(UUID uuid);
Boolean existsByUserAccount(String account);
}
Boolean의 리턴 값을 갖도록 메서드의 이름을 수정해줬다. 이후 테스트를 진행하니 잘 수행되었다~
※ 참고
https://wisdom-cs.tistory.com/66
[Spring Data JPA] 기본 사용법 정리
전에 공부했던 Spring Data JPA의 기본 사용법을 정리하고자 한다. ✔️ Dependency build.gradle 파일의 dependencies 부분에 다음을 추가하자. implementation ‘org.springframework.boot:spring-boot-starter-data-jpa’ ✔️ 공
wisdom-cs.tistory.com
JPA 리포지토리 메서드 이름 명명시 주의하기
JPA 리포지토리에서 메서드를 작성할때는 리턴 타입이 무엇인지에 따라 메서드 명이 바뀌기 때문에 이에 유의해서 메서드 이름을 작성하자 ( 내 맘대로 이름 작성하는거 아님!! )
'프로젝트 활동 > 발생한 문제와 해결 방법' 카테고리의 다른 글
[Postman] Could not send request 에러 (0) | 2024.08.04 |
---|---|
auto-increment 초기화 (0) | 2024.07.20 |
트랜잭션의 중첩으로 인한 문제 (1) | 2024.07.19 |
transaction 에 대하여 (0) | 2024.07.16 |
UnsatisfiedDependencyException (0) | 2024.07.09 |