TIL - 21.01.12

less than 1 minute read

ModelMapper로 서로 다른 필드 맵핑

다음과 같이 UserDTO를 User엔티티로 맵핑하려고 할 때, 서로 다른 필드를 맵핑해야하는 경우
(UserDTO)principar -> (User)email
(UserDTO)credentials -> (User)passwd

  • UserDTO
public class UserDTO {

    private String principal;
    private String credentials;

  • User
public class User {

    @Id
    private Integer seq;
    private String email;
    private String passwd;
    private int loginCount = 0;
    private LocalDateTime lastLoginAt;
    private LocalDateTime createAt;

PropertyMap 으로 맵핑룰을 추가해주면 된다.

@Test
void test_user_model_mapper() {
    UserDTO userDTO = new UserDTO();
    userDTO.setCredentials("haha@test.com");
    userDTO.setPrincipal("qwer");

    PropertyMap<UserDTO, User> userMap = new PropertyMap<UserDTO, User>() {
        @Override
        protected void configure() {
            map().setEmail(source.getPrincipal());
            map().setPasswd(source.getCredentials());
        }
    };
    ModelMapper modelMapper = new ModelMapper();
    modelMapper.addMappings(userMap);

    User user = modelMapper.map(userDTO, User.class);

    assertAll(
            () -> assertEquals(userDTO.getPrincipal(), user.getEmail()),
            () -> assertEquals(userDTO.getCredentials(), user.getPasswd())
    );
}

REF

https://baek.dev/post/15/