mapping of non-iterable to iterable in mapstruct

白昼怎懂夜的黑 提交于 2019-12-11 15:11:40

问题


I am trying to map a non-iterable value i.e. String to a list of string using mapstruct. So I am using

@Mapping(target = "abc", expression = "java(java.util.Arrays.asList(x.getY().getXyz()))")

Here abc is List<String>

xyz is a String

But for this i need to check for null explicitly.

Is there any better way of maaping a non-iterable to iterable by converting non iterable to iterable.


回答1:


Here is an example for non iterable-to-iterable:

public class Source {

    private String myString;

    public String getMyString() {
        return myString;
    }

    public void setMyString(String myString) {
        this.myString = myString;
    }

}

public class Target {

    private List<String> myStrings;

    public List<String> getMyStrings() {
        return myStrings;
    }

    public void setMyStrings(List<String> myStrings) {
        this.myStrings = myStrings;
    }   

}

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

public class NonIterableToIterableUtils {

     @FirstElement
        public List<String> first(String in ) {
            if (StringUtils.isNotEmpty(in)) {
                return Arrays.asList(in);

            } else {
                return null;
            }
        }

}

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

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

    @Mappings( {
        @Mapping( source = "myString", target = "myStrings", qualifiedBy = FirstElement.class )
    } )
    Target toTarget( Source s );
}

public class Main {

    public static void main(String[] args) {
        Source s = new Source();
        s.setMyString("Item");

        Target t = SourceTargetMapper.MAPPER.toTarget( s );
        System.out.println( t.getMyStrings().get(0));

    }

}



回答2:


There is a iterable-to-non-iterable example in the MapStruct examples repository. Addtionally there is a pending pull request for non-iterable-to-iterable.

In a nutshell you can use a custom method that would do the mapping. You can also use @Qualifier to have more granural control



来源:https://stackoverflow.com/questions/47050419/mapping-of-non-iterable-to-iterable-in-mapstruct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!