게시글 CRUD
post 생성 작업
request를 받을때, title / contents 만 입력으로 받고 고정여부는 자동으로 false로 된 채로 만들어지게 하고싶은상황
post 생성자로 entity를 만들때 req만 받아서 isfalse로 하도록 할지...
>> 생성자에서 dto 객체를 통으로 받아 동작하는건 좋지않다고 들었던거 같아서 코드 수정
@Entity 클래스 자체에는 빌더를 선언할수 없지만 생성자에 한정으로 빌더 패턴 가능!
@Builder
public Post(String title, String contents, boolean isPinned, PostType postType) {
this.title = title;
this.contents = contents;
this.isPinned = isPinned;
this.postType = postType;
}
public Post toPostEntity(User user) {
return Post.builder()
.title(title)
.contents(contents)
.isPinned(false)
.postType(PostType.NORMAL)
.user(user)
.build();
}
이후 reqDto에서 빌더패턴을 활용한 toEntity 메서드들을 만들어 상황에 따라 ( 공지글을 만들어야할때 등 )
만들어지는 Post를 정할수 있다
오류발생 1
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : cohttp://m.sparta.storyindays.entity.Post.user -> cohttp://m.sparta.storyindays.entity.User] with root cause
이유 : Spring Framework를 사용한 웹 애플리케이션에서 발생하는 오류 중 하나로 보입니다. 오류 메시지를 분석해보면 TransientPropertyValueException이 발생했으며, 이는 Hibernate와 관련된 오류입니다. 이 오류는 한 객체가 저장되지 않은(transient) 다른 객체를 참조하고 있을 때 발생합니다.
원인 : 현재 db에 User객체가 저장되어 있지 않는데 post객체가 이를 참조하려 해서 발생한 오류였다.
해결 : User객체를 잠시 주석해두고 임시 데이터 사용
post 전체 조회 작업
페이징 기능 구현해야함, 다만 일반 게시글만 페이지 기능 적용
공지글과 상단글은 페이지 적용 X
map 기능으로 Key 값에 따라 구분할 필요 <공지 / 상단 / 일반 >
Value는 List, 다만 일반의 경우 Page<>
Map<String, Iterable<Post>> updateResDtoMap = Map.of("NOTICE", postRepository.findAllByPostType(PostType.NOTICE)
, "NOMAL_TOP", postRepository.findAllByPostTypeAndIsPinned(PostType.NOTICE, true)
, "NOMAL", postRepository.findAllByPostTypeAndIsPinned(PostType.NOTICE, false, pageable));
Map으로 통으로 받아서 return을 해주려고 했으나 재대로 응답에 담길지 불안해 chatGpt의 조언을 받으니
dto로 만들어 return하는것을 추천하여 적용해보았다
@Getter
public class PostGetResDto {
List<PostUpdateResDto> noticePostList;
List<PostUpdateResDto> pinnedPostList;
Page<PostUpdateResDto> postList;
}
게시글 수정 작업
@Transactional
public PostUpdateResDto updatePost(long postId, PostReqDto reqDto) {
// 본인이 작성한 게시글의 수정인 경우만 인가하도록 조건걸기
Post post = findById(postId);
post.update(reqDto);
return new PostUpdateResDto(post);
}
위 코드를 통해 post내용이 바뀐후 db에 적용되는 것까지 확인했으나 post의 modifiedAt값은 바뀌지 않는 문제 발생
원인 : 애너테이션 선언안함, TimeStamps를 상속받은 entity 클래스에 아래의 애너테이션이 선언되어야 JpaAuditing 기능을 사용할수 있다
@EntityListeners(AuditingEntityListener.class)
해결 : 애너테이션 추가
게시글 유저ID 기반 조회 작업
Jpa 쿼리메서드를 다음과 같이 정의했는데 맨 마지막 Post의 FK로 존재하는 User로 필터링해 가져오는게 오류가 발생
Page<Post> findAllByPostTypeAndIsPinnedAndUser(PostType postType, boolean b, Pageable pageable, User user);
게시글 삭제 작업 : 별다른 오류 없이 성공
시큐리티 필터 인증/인가 적용후 테스트
오류발생 2
org.springframework.web.util.pattern.PatternParseException: Missing preceding open capture character before variable name
이유 : URL 패턴을 잘못 정의했을 경우 발생하는 오류
원인 : SecurityConfig에서 requestMatcher( uri ) 부분이 오타가 났다
해결 : 오타 수정
'TIL > Web Back' 카테고리의 다른 글
[Sparta] 내일배움캠프 팀프 회고 (0) | 2024.06.25 |
---|---|
[Sparta] 내일배움캠프 팀프 TIL 3일차 (0) | 2024.06.21 |
[Sparta] 내일배움캠프 팀프 TIL 1일차 (1) | 2024.06.19 |
[Sparta] 내일배움캠프 TIL 35일차 (0) | 2024.06.18 |
[Sparta] 내일배움캠프 TIL 34일차 (0) | 2024.06.17 |