简体   繁体   English

Mapstruct 映射 - 字符串到列表<String>

[英]Mapstruct mapping - String to List<String>

I am struggling to map a string object from source(Relation.class) and to a List of target(RelationListDTO.class) .我正在努力将字符串对象从 source(Relation.class) 映射到目标列表 (RelationListDTO.class) 。

Relation.java关系.java

   public class Relation {

    private String name;
    private String email;
    private String completeAddress;

    // getters and setters
}

RelationListDTO.java RelationListDTO.java

public class RelationListDTO {
        private String name;
        private String email;
        private List<Address> address;

        // getters and setters
    }

Address.java地址.java

public class Address{
private String street;
private String city;
// getters and setters
}

Mapper class映射器类

@Mapper @映射器

public interface RelationMapper {

    @Mapping(source = "completeAddress", target = "address.get(0).city")
            RelationListDTO relationToListDto(Relation relation);
} 

But it is not working.但它不起作用。 Could anyone please help.任何人都可以请帮忙。

What you are trying to do using MapStruct is not possible.您尝试使用 MapStruct 执行的操作是不可能的。 Because MapStruct doesn't work with run time objects.因为 MapStruct 不适用于运行时对象。 MapStruct only generated plain java code for mapping two beans. MapStruct 仅生成用于映射两个 bean 的纯 Java 代码。 And I find your requirement is little unique.我发现你的要求有点独特。 You have a list of Addresses but want to map only city from source object?您有一个地址列表,但只想从源对象映射城市? You can still do like this你仍然可以这样做

@Mapping( target = "address", source = "completeAddress")
RelationListDTO relationToListDto(Relation relation);

// MapStruct will know to use this method to map between a `String` and `List<Address>`
default List<Address> mapAddress(String relation){
      //create new arraylist
      // create new AddressObject and set completeAddress to address.city
     // add that to list and return list

}

Not sure if this was possible at the time of the accepted answer but I had the same problem as you and ended up doing it this way.不确定在接受答案时这是否可行,但我和你有同样的问题,最终以这种方式完成。

@Mapper(imports = Collections.class)
public interface RelationMapper {
    @Mapping(expression = "java(Collections.singletonList(relation.getCompleteAddress()))", target = "address")
            RelationListDTO relationToListDto(Relation relation);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM