【问题标题】:How to tell map function of the MapperModel that specific filed should have specific value?如何告诉 MapperModel 的映射函数特定字段应该具有特定值?
【发布时间】:2021-09-30 07:11:24
【问题描述】:

我在我的项目中使用 ModelMapper 在 DTO 类和模型之间进行映射。

例如:

public class UserDto {
    private String name;
    private String phone;
    private String email;
}

 
public class User {
    @Id
    private String id;
    private String metaDatal;
    private String name;
    private String phone;
    private String email;
}
 

我如何映射它:

@Autowired
private ModelMapper modelMapper;
modelMapper.map(userDto, user);

如您所见,我在用户模型中有 metaDatal 字段,我想将此字段设置为特定值。

映射类的特定字段(metaDatal)我想设置这个值“abc123”。 有什么方法可以告诉 map 方法调用时,特定的字段(例如 metaData)应该具有特定的值(例如 abc123)?

【问题讨论】:

  • metaData 字段初始化为您想要的值。 (并跳过字段typeMap.addMappings(mapper -> mapper.skip(User::setMetaDatal));

标签: java spring mapping modelmapper


【解决方案1】:

我相信最灵活的方法是实现一个简单的Converter。检查这个:

Converter<UserDto, User> metaData = new Converter<UserDto, User>() {
    // This is needed to convert as usual but not having not registered
    // this converter to avoid recursion
    private final ModelMapper mm = new ModelMapper();
    @Override
    public User convert(MappingContext<UserDto, User> context) {
        User u = context.getDestination();
        mm.map(context.getSource(), u);
        u.setMetaDatal("abc123");
        return context.getDestination();
    }
};

现在只需创建一个TypeMap 并设置此转换器来处理转换,例如:

modelMapper.createTypeMap(UserDto.class, User.class).setConverter(metaData);

modelMapper.map()之前。

您还可以在 UserDto 中为元数据添加一个 getter,例如:

public String getMetaDatal() {
    return "abc123";
}

如果是可以直接从UserDto派生的东西,跳过转换器部分。

【讨论】:

    猜你喜欢
    • 2022-07-12
    • 2020-07-18
    • 1970-01-01
    • 2019-06-15
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多