How to capture inheritance data with mapstruct?

Asked

Viewed 12 times

-1

I am creating an API with Spring and there was a need to make inheritance for different types of users. My entity structure follows as follows:

@MappedSuperclass
@Getter
@Setter
@RequiredArgsConstructor
@Inheritance( strategy = InheritanceType.TABLE_PER_CLASS)
public class Profile implements Serializable {
    private static final long serialVersionUID = 7663551134425055595L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String firstName;
    private String lastName;

    @JoinColumn(unique = true,nullable = true)
    @OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
    private Email email;

    @JoinColumn(nullable = true)
    @OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
    private Address address;

}

this class has heirs. such as the next:

@Table(name = "athlete")
@Entity
@Getter
@Setter
@RequiredArgsConstructor
@ToString(onlyExplicitlyIncluded = true)
public class Athlete extends Profile {
    private static final long serialVersionUID = -8638214819876514147L;
    private Double weight;
    private Double height;
}

I’m having difficulty performing the data transfer using the Mapstruct library, because when I request it only receives the methods of the class itself and not the parent class.

@Mapper(componentModel = "spring", uses = {ProfileMapper.class})
public abstract class AthleteMapper{

    public abstract Athlete toModel(AthleteDTO dto);

    @Mapping( target = "athlete.id", source = "email.id")
    public abstract AthleteDTO toDTO(Athlete athlete);
}

The class component is as follows::

@Component
public class AthleteMapperImpl extends AthleteMapper {

    @Override
    public Athlete toModel(AthleteDTO dto) {
        if ( dto == null ) {
            return null;
        }

        Athlete athlete = new Athlete();

        athlete.setId( dto.getId() );
        athlete.setFirstName( dto.getFirstName() );
        athlete.setLastName( dto.getLastName() );
        athlete.setEmail( emailDTOToEmail( dto.getEmail() ) );
        athlete.setAddress( addressDTOToAddress( dto.getAddress() ) );
        athlete.setWeight( dto.getWeight() );
        athlete.setHeight( dto.getHeight() );

        return athlete;
    }

}

The class creates access to the instances that are in composition, but does not create for the inheritance what to do in this situation?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.