orika-mapper / orika

Simpler, better and faster Java bean mapping framework
http://orika-mapper.github.io/orika-docs/
Apache License 2.0
1.29k stars 269 forks source link

Exclude not working if the field is initialized by the chosen constructor #336

Open JohnWu-Pro opened 4 years ago

JohnWu-Pro commented 4 years ago

See the following example. The test will fail because the user.id will be equal to TEST-EMP-1, instead of null. A workaround would be to explicitly specify to use the no-argument constructor.

package org.example.orika;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

public class FieldExclusionTest {

    @Test
    public void testFieldExclusion() {
        Employee employee = new Employee("TEST-EMP-1", "John Doe");

        User user = buildMapper().map(employee, User.class);

        assertThat(user.getId()).isNull();
        assertThat(user.getName()).isEqualTo("John Doe");
    }

    private MapperFacade buildMapper() {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();

        mapperFactory
                .classMap(Employee.class, User.class)
                //.constructorB() // Workaround: explicitly specify to use the no-argument constructor
                .exclude("id")
                .byDefault().register();

        return mapperFactory.getMapperFacade();
    }

    public static class Employee {
        private String id;
        private String name;

        public Employee() {
        }

        public Employee(String id, String name) {
            this.id = id;
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static class User {
        private String id;
        private String name;

        public User() {
        }

        public User(String id, String name) {
            this.id = id;
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}