Search code examples
javamodelmapper

ModelMapper: What is the best way to solve this


I have a problem with ModelMapper library.

Entity classes:

abstract class AbstractEntity {
    Long id;
}
class User extends AbstractEntity {
    String login;
    Business business;
}
class Business extends AbstractEntity {
    String name;
}

Dto classes:

class NewUser {
    String login;
    Long businessId;
}

How I simulate the problem:

public class Main {
    public static void main(String[] args) {
        NewUser newUser = new NewUser();
        newUser.setLogin("jhonatan.serafim");
        newUser.setBusinessId(1L);

        ModelMapper mapper = new ModelMapper();
        User user = mapper.map(newUser, User.class);

        System.out.println(user.getId());
        System.out.println(user.getLogin());
        System.out.println(user.getBusiness().getId());
    }
}

Expected:

null

jhonatan.serafim

1

Actual:

1

jhonatan.serafim

1

What is the best way to solve this?


Solution

  • You can use strict matching strategy:

    mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    

    But in this case user.getBusiness().getId() will fail, because NewUser does not have business field.

    More about matching strategies: ModelMapper – Configuration