ModelMapper:解决这个问题的最佳方法是什么

ModelMapper: What is the best way to solve this

我的 ModelMapper 库有问题。

实体类:

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

Dto 类:

class NewUser {
    String login;
    Long businessId;
}

我是如何模拟问题的:

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());
    }
}

预计:

null

jhonatan.serafim

1

实际:

1

jhonatan.serafim

1

解决这个问题的最佳方法是什么?

为什么您认为 id1?您没有在 NewUser 中将其设置为 1。将它设置在那里,它应该会按预期工作。

可以使用严格匹配策略:

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

但在这种情况下 user.getBusiness().getId() 会失败,因为 NewUser 没有 business 字段。

更多关于匹配策略:ModelMapper – Configuration