문제점
프로젝트를 진행하면서 게시글을 수정, 삭제 api에서 작성자 확인이 제대로 되지 않는 문제가 발생했다.
@Transactional
public PostResponseDto updatePost(Long id, PostRequestDto requestDto, User user) {
Post post = findPost(id);
//게시글 작성자와 요청자가 같은지 또는 관리자인지 체크 -> 아닐시 예외 발생
// 해당 post의 작성자가 맞는지 확인
if (user.equals(post.getUser()) || user.getRole().equals(UserRoleEnum.ADMIN)) {
// requestDto로부터 받은 게시글의 제목과 내용으로 해당 post 내용 수정하기
post.setTitle(requestDto.getTitle());
post.setContent(requestDto.getContent());
Category category = categoryRepository.findById(requestDto.getCategoryId()).orElseThrow(() ->
new IllegalArgumentException("선택한 게시글이 존재하지 않습니다"));
post.setCategory(category);
} else {
// 해당 post의 작성자가 아니라면 null 반환하기
throw new RejectedExecutionException();
}
return new PostResponseDto(post);
}
user.equals(post.getUser())가 계속 false로 나와 이런 문제가 발생했는데 원인은 User 클래스에 equals 메서드를 오버라이딩 해주지 않아서 발생한 거였다.
해결방안
User 클래스에 @EqualsAndHashCode 어노테이션을 달아줌으로써 해결했다.
깨달은 점
두 객체를 equals 메서드로 비교하려면 오버라이딩 하는 걸 잊지 말자!
'TIL > WEEK11' 카테고리의 다른 글
Cascade.REMOVE 와 orphanRemoval (0) | 2023.07.27 |
---|