在进行MapStruct类型转换时,需要对不同的字段类型进行适当的处理。一种解决方法是使用MapStruct中的@Mapping注解来自定义转换逻辑。
示例代码:
源类:
public class Source {
private LocalDateTime time;
private String name;
// 省略getter和setter
}
目标类:
public class Target {
private String time;
private String name;
// 省略getter和setter
}
转换接口:
@Mapper
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);
@Mapping(source = "time", target = "time", qualifiedByName = "localDateTimeToString")
Target toTarget(Source source);
@Named("localDateTimeToString")
static String localDateTimeToString(LocalDateTime source) {
return source.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
}
以上示例中,源类中的time字段是LocalDateTime类型,而目标类中的time字段是String类型。在转换接口中,使用@Mapping注解为字段映射设置对应的转换方式,使用@Named注解来指定自定义的转换方法。这样就能够解决不同字段类型的MapStruct类型转换的问题了。