Model Mapping
๋ชจ๋ธ ๋งคํ์ ์ด๋ Layer ๋จ์์ ๊ตฌํํด์ผํ ๊น?
Servie : ์ฌ๋ฌ ์๋น์ค์์ ์ฌ์ฉ์ ์ค๋ณต์ฝ๋๊ฐ ๋ฐ์ํ๋ฉฐ, ๋ชจ๋ธ๊ฐ ๋งคํ ๋ก์ง์ ๋น์ฆ๋์ค ๋ก์ง์ด ์๋๋ฏ๋ก, ๋ชฉ์ ์ ๋ถํฉํ์ง ์๋๋ค.
Model Object
์๋น์ค๊ฐ ์ปค์ง๊ณ , ๋ชจ๋ธ๊ฐ ๋ค์ํ ๋งคํ์ด ์์ ๊ฒฝ์ฐ ์ ์ ๊ฐ์ฒด์์ ๋ฉ์๋๊ฐ ๋ง์์ง๊ฒ ๋๋ค.
๋ชจ๋ธ ๊ฐ์ฒด์ ๋ชจ๋ธ๊ฐ ๋งคํ ๋ก์ง์ ๋ชจ๋ธ ๊ฐ์ฒด์ ๋ชฉ์ ์ ๋ถํฉํ์ง ์๋๋ค.
Mapper
๋ชจ๋ธ๊ฐ ๋งคํ์ ๋ํ ์ฑ ์์ ์ง๋ค.
์ด๋, ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ด์ฉํด์ ๋ชจ๋ธ๊ฐ ๋งคํ์ ์๋ํํ ๊ฒ์ธ์ง ์ง์ Mapper๋ฅผ ์ด์ฉํด์ ์ฒ๋ฆฌํ ์ง ์ ํด์ผํ๋ค.
ModelMapper
๋ด๋ถ์ ์ผ๋ก Refelction์ ์ฌ์ฉํ๋ฏ๋ก ์ฌ์ฉํ์ง ์๋ ๊ฒ์ด ์ข๋ค.
Reflection์ผ๋ก ์ธํ ์ฑ๋ฅ ์ด์์ ์์์น ๋ชปํ ๊ฒฐ๊ณผ๊ฐ ๋ฐ์ํ ์ ์๋ค.
MapStruct
Reflection์ ์ฌ์ฉํ์ง ์๋๋ค.
์ปดํ์ผ์ ์์ฑํ๋ค.
๊ตญ๋ด๋ ์ ์ง๋ง ๋ฏธ๊ตญ์์ ์ ์ ์ฌ์ฉ๋๊ฐ ๋์์ง๊ณ ์๋ค.
Model Mapper
Entity์ DTO๊ฐ ๊ฐ์ฒด ๋ณํ์ ํ ๋ ModelMapper๋ฅผ ํ์ฉํ๋ฉด, ์ฝ๊ฒ ๋ณํํ ์ ์๋ค.
pom.xml
<!-- model mapper - entity-DTO conversion -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.0</version>
</dependency>
์ฌ์ฉ ๋ฐฉ๋ฒ์ ๊ฐ๋จํ๋ค.
private PaymentDto convertToDto(Payment payment) {
// Entity๋ฅผ DTO๋ก ๋ณํํ๊ธฐ์ํด modelmapper์ฌ์ฉ
ModelMapper modelMapper = new ModelMapper();
PaymentDto paymentDto = modelMapper.map(payment, PaymentDto.class);
return paymentDto;
}
์ฒ์์๋ ์ด๋ ๊ฒ convertToDto ๋ฉ์๋๋ก Entity์์ DTO๋ก ๋ณํํ๋ ์์ ์ ํ์ผ๋, ์ด๊ฒ์ ๋น์ฆ๋์ค ๋ก์ง์ด ์๋๊ธฐ ๋๋ฌธ์ ๋ฐ๋ก Mapperํด๋์ค๋ฅผ ์์ฑํ๋ ๊ฒ์ด ์ข๋ค.
MapStruct
pom.xml
<!-- mapStruct - Entity to Dto-->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.3.1.Final</version>
</dependency>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.1.Final</version>
</path>
<!-- other annotation processors -->
</annotationProcessorPaths>
</configuration>
</plugin>
EntityMapper
import java.util.List;
public interface EntityMapper <D, E>{
E toEntity(D dto);
D toDto(E entity);
List<D> toDtoList(List<E> entity);
}
PaymentMapper
@Mapper(componentModel = "spring")
public interface PaymentMapper extends EntityMapper<PaymentDto, Payment> {
}
Service
@Autowired
private PaymentMapper paymentMapper;
@Override
@Transactional
public PaymentDto cancelRequest(String mbrId, String pmtId, long pmtAmt, Boolean isParticleCancle) {
// ...
Payment result = paymentRepository.save(newPayment);
PaymentDto paymentDto = paymentMapper.toDto(result);
return paymentDto;
}
์ด๋ ๊ฒ ์ฌ์ฉํ๋ฉด๋๋ค. ๋ง์ฝ์ ๋ณ์๋ช ์ด ๋ค๋ฅด๋ค๋ฉด, @Mapping annotation์ผ๋ก ์ฝ๊ฒ ๋ฐ๊ฟ ์ ์๋ค.
์ฐธ์กฐ
Last updated
Was this helpful?