DTO <-> Entity 변환
Entity 와 DTO는 분리하여 사용하는것이 좋기 때문에 분리해서 사용하다 보면 각 객체간에 어떻게 변환을 하는지에 대해서 의문점이 생길것이다.
'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 라이브러리 추가
implementation group : 'org.modelmapper', name : 'modelmapper', version : '2.3.8'
(2) 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 코드 작성
@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;
}
}