1. @Builder 란?
생성자/빌더 패턴을 자동으로 만들어 주는 Lombok 어노테이션이다.
BoardDto dto = BoardDto.builder()
.userId(123L)
.nickname("홍길동")
.title("제목")
.build();
객체 생성시 위와 같이 필드명.값 형태로 가독성 높게 객체를 만들 수 있다.
2. @Builder(toBuilder = true)
toBuilder = true를 쓰면 이미 만들어진 객체에서 일부 값만 바꿔서 새 객체를 만드는 빌더를 자동으로 추가해준다.
BoardDto a = BoardDto.builder()
.userId(1L)
.nickname("닉네임")
.title("제목1")
.build();
BoardDto b = a.toBuilder()
.title("제목2")
.build();
a 를 복사해서(title만 바꿔서) b라는 새 객체 생성
나머지 값(userId, nickname 등)은 그대로 복사됨
3. @Builder(toBuilder = true)를 많이 쓰는 이유
불변(immutable) 객체를 선호할 때
원본 DTO/List를 손대지 않고 새 객체를 만들 때
map(dto -> dto.toBuilder().userId(XXX).build()) 처럼 리스트 일괄 가공(특히 컨트롤러, 서비스 계층에서)할 때 매우 편리하다.
4 사용 예시
boardDtoList.forEach(boardService::createBoard); //반복 insert
return ResponseEntity.ok().build();
기존에 이렇게 작성한 코드가 있었다.
이 부분을 다음과 같이 수정하였다.
List<BoardDto> fixedDtoList = boardDtoList.stream()
.map(dto -> BoardDto.builder()
.boardId(dto.getBoardId())
.userId(userId)
.nickname(nickname)
.title(dto.getTitle())
.content(dto.getContent())
.emotionalScore(dto.getEmotionalScore())
.empathyCount(dto.getEmpathyCount())
.viewCount(dto.getViewCount())
.autonomousDistrict(dto.getAutonomousDistrict())
.administrativeDistrict(dto.getAdministrativeDistrict())
.createdDate(dto.getCreatedDate())
.modifiedDate(dto.getModifiedDate())
.build())
.toList();
fixedDtoList.forEach(boardService::createBoard);
return ResponseEntity.ok().build();
'tech > Spring' 카테고리의 다른 글
| Java에서 컬렉션 sort 동작 방식 (0) | 2025.11.05 |
|---|---|
| [Spring] @ActiveProfiles("test") vs @DataJpaTest (0) | 2025.08.21 |
| [Spring] 좋은 AppConfig 설계 (0) | 2025.07.19 |
| [Spring] N + 1 문제 (1) | 2025.07.18 |
| [Spring] Config (0) | 2025.07.09 |