java - 使用 org.modelmapper.modelmapper 进行对象映射

标签 java modelmapper

我有 2 个对象:

@Setter
@Getter
public class Agent {
    public int userID;
    public String name;
    public boolean isVoiceRecorded;
    public boolean isScreenRecorded;
    public boolean isOnCall;
    public LocalDateTime startEventDateTime;
}
public class AgentLine {
    public int userID;
    public String name;
    public boolean isVoiceRecorded;
    public boolean isScreenRecorded;
    public boolean isOnCall;
    public String startEventDateTime;
}

我想在 AgentLine 和 Agent 之间进行映射。由于 Localdatetime 转换,我无法使用默认映射。 我已经定义:

    @Bean
    ModelMapper getModelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        Converter<AgentLine, Agent> orderConverter = new Converter<AgentLine, Agent>() {
            @Override
            public Agent convert(MappingContext<AgentLine, Agent> mappingContext) {
                AgentLine s = mappingContext.getSource();
                Agent d = mappingContext.getDestination();
/*                d.userID = s.userID;
                d.name = s.name;*/
                d.startEventDateTime = LocalDateTime.parse(s.startEventDateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                return d;
            }
        };
        modelMapper.addConverter(orderConverter);
        return modelMapper;
    }

为了使用它:

AgentLine line;
@Autowired
private ModelMapper modelMapper;
Agent agent = modelMapper.map(line, Agent.class);

它有效,但我不想在转换方法中指定所有代理属性,我想指定 startEventDateTime 转换,并且默认情况下将映射其余属性。

此外我尝试定义:

PropertyMap<AgentLine, Agent> orderMap = new PropertyMap<AgentLine, Agent>() {
                @Override
                protected void configure() {
                    map().setName(source.name);
                }
            };
modelMapper.addMappings(orderMap);

但是,在映射中您无法处理日期转换。 如果我为映射器 PropertyMap 和 Converter 定义,则 PropertyMap 将被忽略。

我不想在转换方法中指定所有代理属性,我想指定 startEventDateTime 转换,其余属性将默认映射。

最佳答案

不要使用Converter来映射复杂对象。您应该使用 TypeMap 来实现此类目的。使用 Converter 进行自定义转换(对于您的情况,将 String 转换为 LocalDateTime)。

ModelMapper modelMapper = new ModelMapper();    
Converter<String, LocalDateTime> dateTimeConverter = ctx -> ctx.getSource() == null ? null : LocalDateTime.parse(ctx.getSource(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
modelMapper.typeMap(AgentLine.class, Agent.class)
        .addMappings(mapper -> mapper.using(dateTimeConverter).map(AgentLine::getStartEventDateTime, Agent::setStartEventDateTime));

关于java - 使用 org.modelmapper.modelmapper 进行对象映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041483/

相关文章:

java - Lookup.getDefault().lookup() 返回 null

java - Spring Cloud Stream 的 OUTPUT channel 的并发(线程执行器)

java - 具有严格匹配策略的 ModelMapper

java - 从实体映射到 DTO 时,ModelMapper 在 DTO 字段中返回 Null

java - 重定向时 URL 中的冒号?

java - 字段超出范围java

java - ModelMapper:将集合映射到其他结构的集合

java - 模型映射器 - 如何映射不兼容的类型

java - 在标准输出中打印数字的程序

java - 如何在模型映射器中跳过目标源中的属性?