부모엔티티와 자식엔티티 그리고 NullPointerException

시은·2024년 2월 18일
0
post-thumbnail

갑자기 NullPointerException 이? 😮

게시글을 생성 요청을 보냈는데, 아래와 같은 에러가 절 반겨주었습니다.

java.lang.NullPointerException: Cannot invoke "java.util.List.add(Object)" because "this.hashTags" is null
	at com.example.feedservice.domain.post.domain.Post.mappingHashTag(Post.java:46) ~[classes/:na]
	at com.example.feedservice.domain.hashtag.HashTag.mappingPost(HashTag.java:34) ~[classes/:na]
	at com.example.feedservice.domain.post.service.PostService.createPost(PostService.java:86) ~[classes/:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]

에러로그를 찬찬히 살펴보니 해시태그 리스트 생성에 문제가 생긴모양❗

바로 달려가서 코드를 살펴보았습니다. 틀린게 없다고 생각이 들었지만, this.hashTags 가 null 이라는데…

@Transactional
public PostResponse createPost(PostCreateRequest postCreateRequest) {
		User user = authUtil.getLoginUser()
		    .orElseThrow(() -> new ApiException(ErrorType.USER_NOT_FOUND));

    Post createPost = Post.builder()
            .title(postCreateRequest.getTitle())
            .description(postCreateRequest.getDescription())
            .shareCount(0L)
            .viewCount(0L)
            .heartCount(0L)
            .user(user)
            .createdAt(LocalDateTime.now())
            .build();

    postRepository.save(createPost);

    String[] words = postCreateRequest.getHashTags().split(" ");
    for (String word : words) {
        if (word.startsWith("#") && word.length() > 1) {
            word = word.substring(1);

            HashTag hashTag = HashTag.builder()
                    .hashTag(word)
                    .build();
            hashTag.mappingPost(createPost);
            hashTagRepository.save(hashTag);
        }
    }

    List<String[]> hashTags = new ArrayList<>();
    for (HashTag temp : createPost.getHashTags()) {
        hashTags.add(new String[]{String.valueOf(temp.getId()), temp.getHashTag()});
    }

    PostResponse postResponse = PostResponse.builder()
            .id(createPost.getId())
            .title(createPost.getTitle())
            .description(createPost.getDescription())
            .hashTags(hashTags)
            .heartCount(createPost.getHeartCount())
            .shareCount(createPost.getShareCount())
            .viewCount(createPost.getViewCount())
            .createdAt(createPost.getCreatedAt())
            .build();
        
    return postResponse;
}

문제의 원인은 포스트를 생성하는 곳에 있었습니다. 아래에서 해시태그를 매핑하고, 저장했기 때문에 괜찮겠지 라고 생각했지만 그게 아니였습니다❗ 

아래와 같이 모든 값을 다 만들어주고줘야 합니다. hashTag 와 같이 생성된 후에 처리해야 하는경우에는 new ArrayList<>() 를 넣어주세요.

Post createPost = Post.builder()
            .title(postCreateRequest.getTitle())
            .description(postCreateRequest.getDescription())
            .shareCount(0L)
            .viewCount(0L)
            .heartCount(0L)
            .hashTags(new ArrayList<>())
            .user(user)
            .createdAt(LocalDateTime.now())
            .build();

결과

profile
창의력 대장이 되기 위한 여정

0개의 댓글