Spring Boot
@Builder 사용시 초기화 필드는 어떻게 될까?
kkkkkkkkkkkk
2022. 9. 5. 12:24
Account 클래스는 컬렉션을 참조하고 있고 null 방지를 위해 필드에서 초기화를 진행한 엔티티에 Tag 를 컬렉션에 추가하는 상황에 null 이 발생하는 이슈를 정리하는 글입니다.
아래와 같은 Account 클래스가 있다.
@Builder
@Entity
public class Account {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToMany
private Set<Tag> tags = new HashSet<>();
}
위의 Account 클래스를 빌더로 인스턴스를 생성하여 저장하고 Tag 도 저장한다.
@DisplayName("계정에 태그를 추가하는 테스트")
@Test
@Transactional
void addTag() {
Account account = Account.builder().nickname("이기영").build();
accountRepository.save(account);
TagForm tagForm = new TagForm();
tagForm.setTagTitle("spring");
Tag tag = tagRepository.save(tagForm.toEntity());
accountRepository.findById(1L).ifPresent(a -> a.getTags().add(tag));
}
하지만 NullPoint 가 발생한다.
null이 왜 발생할까?
@Buillder 는 클래스를 빌더패턴으로 생성할 수 있게 도와주는 애노테이션이다. 위의 Account 클래스 필드의 Tag 컬렉션을 필드에서 바로 초기화를 진행 했다.
이러한 필드에서 초기화된 상태는 @Builder 애노테이션에서 무시가 된다.
빌더로 초기화를 하던가 아니면 해당 필드에 @Builder.Default 로 해당 기본값으로 설정 해주면 null로 초기화가 되던 상황을 피할 수 있다.