jpa
saveAll()을 사용하기 위해 List<DTO>를 List<Entity>로 변환
원코드
2022. 11. 3. 15:10
스트림을 이용해서 변환해주면 된다
------------------Dto 클래스 ------------------
@Getter
@NoArgsConstructor
public class GoalsSaveRequestDto {
private String text; // 목표 내용
private String state; // 목표 상태 - 목표, 성공, 실패
private String userId; // 사용자
@Builder
public GoalsSaveRequestDto(String text, String state, String userId) {
this.text = text;
this.state = state;
this.userId = userId;
}
public Goals toEntity() {
return Goals.builder()
.state(state)
.text(text)
.userId(userId)
.build();
}
}
----------------Service 클래스 ----------------
@Transactional
public int save(List<GoalsSaveRequestDto> requestDto) {
List<Entity> EntityList = requestDto.stream()
.map(GoalsSaveRequestDto::toEntity)
.collect(Collectors.toList());
return repository.saveAll(EntityList).size();
}
참고:
[Spring Data JPA] JPA Entity, Repository, Service 클래스 작성 (조회 및 저장) - QuickStart 2
2021.12.12 - [Spring/Spring Data JPA] - [Spring Data JPA] 예제 프로젝트 생성 및 초기 환경 구성 - QuickStart 1 이전글의 내용을 이어서 작성합니다. # 해당 시리즈 게시글은 Notion에서 작성된 내용을 그대로 옮겨
antdev.tistory.com