Skip to content
Advertisement

Unable to map target properties using constructors with mapstruct

I am using MapStruct 1.5.2.Final

Map struct is unable to map the target values using the parameterised constructor. Following is the parameterised constructor for the class.

I know that if I would have exposed the setters, this would have worked.

I don’t want to expose the setters for my class as I want my class to be immutable.

@JsonCreator
public PassengerInfo(
        @JsonProperty("a") final String a,
        @JsonProperty("b") final String b) {
    this.a = a;
    this.b = b;
}

I am getting the following error

error: Property "a" has no write accessor in class.
error: Property "b" has no write accessor in class.

Also, this is the only constructor in my class.

Following is my class

    public class Clazz {

    private final String a;

    private final String b;

    @JsonCreator
    public Clazz(
            @JsonProperty("a") final String a,
            @JsonProperty("b") final String b) {
        this.a = a;
        this.b = b;
    }

    public String getA() {
        return a;
    }

    public String getB() {
        return b;
    }
    
}

Advertisement

Answer

Your code seems fine. There must be something else in your project.

@Getter
@Setter
public class PassengerEntity {
    private String a;
    private String b;
}

public class PassengerInfo {
    private final String a;
    private final String b;

    @JsonCreator
    public PassengerInfo(
            @JsonProperty("a") final String a,
            @JsonProperty("b") final String b) {
        this.a = a;
        this.b = b;
    }

    public String getA() {
        return a;
    }

    public String getB() {
        return b;
    }
}

@Mapper
public interface PassengerMapper {
    PassengerInfo mapPassenger(PassengerEntity entity);
}

class PassengerMapperTest {

    private PassengerMapper passengerMapper;

    @BeforeEach
    void setUp() {
        passengerMapper = Mappers.getMapper(PassengerMapper.class);
    }

    @Test
    void testMapper() {
        PassengerEntity entity = new PassengerEntity();
        entity.setA("valueA");
        entity.setB("valueB");

        PassengerInfo info = passengerMapper.mapPassenger(entity);

        Assertions.assertEquals("valueA", info.getA());
        Assertions.assertEquals("valueB", info.getB());
    }
}

=> test is OK

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement