2017-02-14 298 views
1

我目前有一个Map<String, String>,它包含key = value形式的值,我想将它们“扩展”为真实的对象。MapStruct:从java.util.Map到Bean的映射?

是否可以使用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; 
} 
+0

我认为目前这在MapStruct中是不可能的。但是,它看起来很有趣。你可以在MapStruct [问题跟踪器](https://github.com/mapstruct/mapstruct/issues)中创建一个问题作为一个新功能,如果人们对它感兴趣,它可能会被添加。 – Filip

回答

0

方法1

的MapStruct回购为我们提供了有用的例子如Mapping from map

从java.util.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); 
} 

注意使用MappingUtil类的帮助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"); 
    } 
} 

方法2

按Raild评论the issue related to this post,可以使用MapSt构作表达式实现在更短的方式类似的结果:

@Mapping(expression = "java(parameters.get(\"name\"))", target = "name") 
public MyEntity mapToEntity(final Map<String, String> parameters); 

没有注意到对性能虽然和类型转换可能是这样的麻烦,但一个简单的串来串映射,它看起来更清洁。