ETC

ModelMapper

버스는그만 2023. 8. 20. 22:20

어떤 Object(Source Object)에 있는 필드 값들을 자동으로 원하는 Object(Destination Object)에

Mapping 시켜주는 라이브러리이다.

 

그렇다면 왜 사용할까?

DTO와 같은 클래스로 데이터를 받은 후 원하는 클래스(엔티티)에 넣어줄 때, 하나씩 넣어준다면?

이때 문제가 발생한다.

  • 매우 귀찮다.
  • 실수가 발생할 수 있다.

의존성 추가

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

빈 등록

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

사용

@RequiredArgsConstructor
@RestController
@RequestMapping("/")
public class UserController {
    private final UserService userService;


    @PostMapping("/users")
    public ResponseEntity createUser(@RequestBody RequestUser user) {
        ModelMapper mapper = new ModelMapper();
        mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

        UserDto userDto = mapper.map(user, UserDto.class);
        userService.createUser(userDto);

        ResponseUser responseUser = mapper.map(userDto, ResponseUser.class);
        return ResponseEntity.status(HttpStatus.CREATED).body(responseUser);
    }
}

전략

modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD) // STANDARD 전략
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE) // LOOSE 전략
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT) // STRICT 전략
  • MatchingStrategies.STANDARD(default)
    • 모든 destination 객체의 property 토큰들은 매칭 되어야 한다.
    • 모든 source 객체의 property들은 하나 이상의 토큰이 매칭되어야 한다.
    • 토큰은 어떤 순서로든 일치될 수 있다.
  • MatchingStrategies.STRICT
    • 가장 엄격한 전략
    • source와 destination의 타입과 필드명이 같을 때만 변환
    • 의도하지 않은 매핑이 일어나는 것을 방지할 때 사용
  • MatchingStrategies.LOOSE
    • 가장 느슨한 전략
    • 토큰을 어떤 순서로도 일치 시킬 수 있다.
    • 마지막 destination 필드명은 모든 토큰이 일치해야 한다.
    • 마지막 source 필드명에는 일치하는 토큰이 하나 이상 있어야 한다.

참고자료

https://squirmm.tistory.com/entry/Spring-modelMapper