[Java] Entity <-> DTO 변환(ToDamin 메서드 & Model Mapper)

김탁형·2024년 6월 29일

DTO <-> Entity 변환
Entity 와 DTO는 분리하여 사용하는것이 좋기 때문에 분리해서 사용하다 보면 각 객체간에 어떻게 변환을 하는지에 대해서 의문점이 생길것이다.

  1. DTO 내부 메서드로 값을 전달하는 방법.
  2. Model Mapper 라이브러리를 사용하는 방법.
  3. DTO, Entity 내부 편의 메서드 작성법

'Entity'

@Getter
@Setter
@Builder
@Entity
@Table(name="lecture")
@AllArgsConstructor
@NoArgsConstructor
public class LectureEntity{

    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    Long lectureId; // 고유 번호
    LocalDate lectureDate;
    @ColumnDefault("0") // defalut 0
    Long CurrentStudentCount; // 특강 신청 인원
    
       public LectureDomain toDomain(){ // Enity -> Domain
 		    LectureDomain lectureDomain = new LectureDomain();
      	 	BeanUtils.copyProperties(this, lectureDomain);
       		return lectureDomain;
    }

    
}

'Repositry'

public LectureDomain save(LocalDate lectureDate){
        LectureEntity lectureEntity
                = lectureJpaRepository.save(
                        LectureEntity.builder().lectureDate(lectureDate).build());
        return lectureEntity.toDomain(); // Enity > Domain 컨버팅
    }

'Domain'

@Getter
@Setter
public class LectureDomain {
    Long lectureId; // 고유 번호
    LocalDate lectureDate; // 강의 날짜
    Long CurrentStudentCount; // 특강 신청 인원

    public LectureListDto toDTO(){ // Domain -> DTO
        LectureListDto lectureListDto = new LectureListDto();
        BeanUtils.copyProperties(this, lectureListDto);
        return lectureListDto;
    }
 }

'Service'

 @Override
    @Transactional
    public LectureDto apply(Long userId, Long lectureId) {
            LectureApplicationDomain lectureApplicationDomain
                = lectureApplicationRepository.save(userId, lectureId);
        return lectureApplicationDomain.toDTO(); // Domain > DTO 컨버팅
    
  1. Model Mapper 사용(직접 코딩하여 작성예정)
  • Model Mapper 라는 라이브러리를 사용하여 간단하게 변환하는 방법이다.
  • 해당 라이브러리를 사용하려면 DTO,Entity 의 필드가 동일해야 에러가 발생하지 않는다.
  • 만약 데이터를 별도로 가공해야한다면 DTO Inner Class 를 생성하여 사용하는 것을 추천한다.

(1) Model Mapper 라이브러리 추가

implementation group : 'org.modelmapper', name : 'modelmapper', version : '2.3.8' 

(2) config 파일 생성

  • Mopdel Mapper 를 상용하기 위해서는 config
package org.hhplus.cleanarchitucture.lectures.tool;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ModelConfig {

    //Model Mapper
    @Bean
    public ModelMapper modelMapper(){
        return new ModelMapper;
    }
}

(3) Servcie 코드 작성

  • model Mapper 를 사용하기 위해서 DI(Dependency Injection) 주입
  • modelMapper.map 사용
    인자의 첫번째는 바꿀 객체, 두번째는 어던 타입으로 변경할건지에 대한 객체 이다.
  • 응용하면 순서만 바꾼채로 변환이 가능하다.
@Service
@RequiredArgsConstructor
public class BoardService{
	private final BoardRepository repository;
    private final ModelMapper modelMapper;
    
    public BoardDTO savePost2(BoardDTO boardDTO) {
    // DTO to Entity
    Board entity = modelMapper.map(boardDTO, Board.class)
    
    //save
    Board SaveEntity = repository.save(entity)
    
    // Entity To DTO
    BoardDTO dto = modelMapper.map(saveEntity, Board.class)
    
    return dto;
    }
}
profile
김탁형/성남/31

0개의 댓글