Skip to content

defaultExpression does not work when mapping a collection of custom types #3159

@pwinckles

Description

@pwinckles

Expected behavior

defaultExpression does not default a property when the source property is null when there is a conversion between the source and the destination types. See the example I provided. defaultExpression does work as expected when the no conversion is necessary, such as string to string.

Actual behavior

Instead of setting the property to an empty list, it sets it to null.

Steps to reproduce the problem

@Mapper
public abstract class ExampleMapper {

    public static class Example {
        public static class Thing {
            private String value;

            public String getValue() {
                return value;
            }

            public void setValue(String value) {
                this.value = value;
            }
        }

        private List<Thing> list;

        public List<Thing> getList() {
            return list;
        }

        public void setList(List<Thing> list) {
            this.list = list;
        }
    }

    public static class ExampleDto {
        public static class ThingDto {
            private String value;

            public String getValue() {
                return value;
            }

            public void setValue(String value) {
                this.value = value;
            }
        }

        private List<ThingDto> list;

        public List<ThingDto> getList() {
            return list;
        }

        public void setList(List<ThingDto> list) {
            this.list = list;
        }
    }

    @Mapping(target = "list", source = "list", defaultExpression = "java(new ArrayList<>())")
    public abstract ExampleDto map(Example example);

    public static void main(String[] args) {
        var mapper = Mappers.getMapper(ExampleMapper.class);

        var example = mapper.map(new Example());

        // This produces: list: null
        System.out.println("list: " + example.getList());
    }

}

MapStruct Version

1.5.3.FINAL

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions