Spring

[템플릿] DTO to Entity, Entity to DTO

Lea Hwang 2023. 4. 17. 11:11

Entity를 DTO로 변환시키거나, DTO를 Entity로 변환시킬 때 사용하는 기본 코드입니다. 

 

 

Entity to DTO

@Entity
public class Something {
		...

		private String name;

		private String email;

		...

		public SomethingResponseDto toResponseDto(){
                    return SomethingResponseDto.builder()
                            .name(name)
                            .email(email)
                            .build();
    }
}

 

사용하는 방법

SomethingResponseDto responseDto = something.toResponseDto();

 

 

Entity to DTO List

사용하는 방법

List<SomethingResponseDto> responseDtoList =
        somethingRepository.findAll()
                .stream()
                .map(Something::toResponseDto)
                .collect(Collectors.toList());

 

또는 

List<SomethingResponseDto> responseDtoList =
    somethingRepository.findAllByOrderByIdDesc()
                    .stream()
                    .map(something -> SomethingResponseDto.builder()
                        .name(something.getName())
                        .email(something.getEmail())
                        .build()
    ).collect(Collectors.toList());

 

 

RequestDTO to Entity

public class SomethingRequestDto {

    private String name;

    private String email;

    public Something toEntity(){
            return Something.builber()
                        .name(name)
                        .email(email)
                        .build();
    }
}

 

사용하는 방법

Something something = somethingRequestDto.toEntity();