Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map abstract class to DTO with MapStruct

I found a lot of topics to this but all solutions went into a wrong direction in my eyes.

So... How do i use MapStruct mapping for this case?

abstract class Person:

public abstract class Person implements Serializable{

     private String name;
     private String somethingToIgnore

     //Getter and Setter

}

The normal Mapper doesn´t work:

@Mapper(componentModel = 'cdi')
public interface PersonMapper{

    @Mapping(target = 'somethingToIgnore', ignore = 'true')
    Person toPerson(PersonDTO source);

    @InheritInverseConfiguration
    PersonDTO toPersonDtO(Person source);

}

I am not allowed to map an abstract class. I should use the a factory method. I tried but i simply have no clue how this factoy method should look like...

My attempt:

@Mapper
public interface PersonMapper {

    PersonMapper INSTANCE = Mappers.getMapper( PersonMapper.class );

    Person toPerson(PersonDTO source);

    PersonDTO toPersonDtO(Person source);
}

@Mapper
public abstract class PersonMapper {

    public static final PersonMapper INSTANCE = Mappers.getMapper( PersonMapper.class );

    Person toPerson(PersonDTO source);

    PersonDTO toPersonDtO(Person source);
}

What am i missing and doing wrong ? Thanks in advance.

like image 360
albert Avatar asked Oct 20 '25 15:10

albert


1 Answers

MapStruct doesn't know how to map to abstract class, because it cannot instantiate it. I expect that you have some implementation of Person. You need to provide method which will create object of a Person like this:

@Mapper
public interface PersonMapper {

    Person toPerson(PersonDTO source);

    PersonDTO toPersonDtO(Person source);

    default Person createPerson() {
        return new PersonImpl();
    }
}

This way MapStruct will use this method to create Person instance and than map the properties like usual. You can find more about object factories in the documentation.

like image 144
Tuom Avatar answered Oct 22 '25 04:10

Tuom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!