ModelMapper /MapStruct

Shaun·2022년 1월 23일
1

SpringBoot

목록 보기
5/20

항상 엔티티에서 뷰단으로 넘어가면서 dto ->Entity / Entity -> Dto로 변환이 반복적이고 귀찮아서 뭐좋은거 없나 하다가 찾던도중에 하나를 발견해서 포스팅한다!

ModelMapper

http://modelmapper.org/

객체의 프로퍼티를 다른 객체의 프로퍼티로 맵핑해주는 유틸리티

ModelMapper 란 서로 다른 object 간의 필드 값을 자동으로 mapping 해주는 library

언제 사용할까?
예를들어 Springboot + jpa 로 개발할 경우 Entity 와 view layer에서 사용될 data object가 구분된다. 따라서 Entity의 값을 view layer에 전달할 경우 data object 로 새로 변환해주는 작업을 해야한다. 일반적으로 getter/setter 또는 Builder 패턴을 통하여 해당 작업을 할 경우 필드가 많을 수록 코드가 길어지고 반복적인 작업량이 늘어난다.

    TestEntity testEntity = testRepository.findById("test");

    TestDto testDto = new TestDto();
    testDto.setEmail(testEntity.getEmail());
    testDto.setGender(testEntity.getGender());
    testDto.setId(testEntity.getId());
    
    // ...
    

반복적인 object 간 변환을 간단하게 줄이고 싶을 때 ModelMapper 를 사용할 수 있다!

사용법

의존성 주입.

maven

< dependency>
< groupId>org.modelmapper< /groupId>
< artifactId>modelmapper< /artifactId>
< version>2.3.8< /version>
< /dependency>

gradle

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

Spring Bean 등록

매번 ModelMapper 를 생성하여 사용할 수 있지만, 반복적으로 여러 로직에서 사용됨으로 @Bean 으로 등록하여 사용하자.

@Configuration
public class AppConfig {

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

}
사용 방법
data 의 원본이 되는 source 와 기존 객체에 매핍할 경우 해당 객체를, 새로운 객체를 생성할 경우 생성할 객체의 class 를 전달하면 된다.

TestEntity testEntity = testRepository.findById("test");

TestDto testDto = modelMapper.map(testEntity, TestDto.class);

// TestDto testDto = new TestDto();
// testDto.setEmail(testEntity.getEmail());
// testDto.setGender(testEntity.getGender());
// testDto.setId(testEntity.getId());
추가적으로 특정 필드 skip, Null인 필드, source와 destination 객체 간의 필드가 다를 경우 등 다양한 상황에 대한 handling 방법이 있다. 해당 내용은 http://modelmapper.org/ 에서 직접 확인 해보면서 사용하는 것이 좋다.

출처:https://velog.io/@kimview/ModelMapper
출처:https://velog.io/@sdb016/ModelMapper

MapStruct

MapStruct
MapStruct2

profile
호주쉐프에서 개발자까지..

0개의 댓글