MapStruct:从java.util.Map到Bean的映射?

时间:2017-02-14 12:59:12

标签: java mapstruct

我目前有一个Map<String, String>,其中包含key = value形式的值,我想将它们“扩展”为真实对象。

是否可以使用MapStruct自动执行该操作,我该怎么做?

澄清一下:我手写的代码看起来像这样:

public MyEntity mapToEntity(final Map<String, String> parameters) {
  final MyEntity result = new MyEntity();
  result.setNote(parameters.get("note"));
  result.setDate(convertStringToDate(parameters.get("date")));
  result.setCustomer(mapIdToCustomer(parameters.get("customerId")));
  // ...
  return result;
}

1 个答案:

答案 0 :(得分:3)

方法1

MapStruct repo为我们提供了有用的示例,例如Mapping from map

从java.util.Map映射bean看起来像:

Dictionary<string, string> _addressBook = new Dictionary<string,string>();

请注意使用MappingUtil类来帮助MapStruct确定如何从Map中正确提取值:

@Mapper(uses = MappingUtil.class )
public interface SourceTargetMapper {

    SourceTargetMapper MAPPER = Mappers.getMapper( SourceTargetMapper.class );

    @Mappings({
        @Mapping(source = "map", target = "ip", qualifiedBy = Ip.class),
        @Mapping(source = "map", target = "server", qualifiedBy = Server.class),
    })
    Target toTarget(Source s);
}

方法2

根据Raild对the issue related to this post的评论,可以使用MapStruct表达式以更短的方式获得类似的结果:

public class MappingUtil {

    @Qualifier
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.SOURCE)
    public @interface Ip {
    }

    @Qualifier
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.SOURCE)
    public static @interface Server {
    }

    @Ip
    public String ip(Map<String, Object> in) {
        return (String) in.get("ip");
    }

    @Server
    public String server(Map<String, Object> in) {
        return (String) in.get("server");
    }
}

虽然没有关于性能的说明,并且类型转换可能比较简单,但对于简单的字符串到字符串映射,它确实看起来更干净。