我有两个对象:
@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);
它有效,但我不想在convert方法中指定所有代理属性,我想指定startEventDateTime转换,默认情况下会映射其余的属性。
另外我试图定义:
PropertyMap<AgentLine, Agent> orderMap = new PropertyMap<AgentLine, Agent>() {
@Override
protected void configure() {
map().setName(source.name);
}
};
modelMapper.addMappings(orderMap);
但是,在映射中,您无法处理日期转换。 如果我为映射器定义PropertyMap和Converter,则忽略PropertyMap。
我不想在convert方法中指定所有代理属性,我想指定startEventDateTime转换,默认情况下会映射其余的属性。
答案 0 :(得分:1)
不要使用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));