Al Grant
Al Grant

Reputation: 2354

MapStruct passing in multiple objects error

I have trying to pass in two Entities as parameters to MapStruct but when I do I get compile error Method has no source parameter named "bird". Method source parameters are: "healthCheck, transmitter"

The MapStruct method works fine on its own with just HealthCheck parameter:

@Mapping(source = "bird.name", target = "name")
@Mapping(source = "location.x", target = "latitude")
@Mapping(source = "location.y", target = "longitude")
HealthCheckViewDTO healthCheckToHealthCheckViewDTO(HealthCheck healthCheck);

But as soon as I add transmitter as a second parameter it complains about bird as a missing parameter. (Bird is a parent of HealthCheck).

@Mapping(source = "bird.name", target = "name")
@Mapping(source = "location.x", target = "latitude")
@Mapping(source = "location.y", target = "longitude")
HealthCheckViewDTO healthCheckToHealthCheckViewDTO(HealthCheck healthCheck, Transmitter transmitter);

HealthCheck Entity

@Entity
@Data
public class HealthCheck {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private Bird bird;

HealthCheckViewDTO

@Data
public class HealthCheckViewDTO {
    private Long id;
    private String name;
    private LocalDate catchDate;
    private Double longitude;
    private Double latitude;
    private TransmitterOnHealthCheckDTO transmitter;

TransmitterOnHealthCheckDTO

@Data
public class TransmitterOnHealthCheckDTO {

private Long id;
private Integer channel;
private LocalDate dateAttached;
private String comment;

If I manually construct TransmitterViewDTO on the service layer it is fine:

healthCheckViewDTO = healthCheckMapper.healthCheckToHealthCheckViewDTO(healthCheck);
transmitterOnHealthCheckDTO = transmitterMapper.transmitterToTransmitterOnHealthCheckDTO(transmitter);
healthCheckViewDTO.setTransmitter(transmitterOnHealthCheckDTO);
return healthCheckViewDTO;

Why is it failing with Method has no source parameter named "bird". Method source parameters are: "healthCheck, transmitter" when I add transmitter as a second parameter?

Upvotes: 1

Views: 1673

Answers (1)

Al Grant
Al Grant

Reputation: 2354

The answer is that when you start to pass in more than one object the names must become fully qualified in your Mapper class.

In other words @Mapping(source = "bird.name", target = "name") becomes @Mapping(source = "healthCheck.bird.name", target = "name")

So my @Mappings had to change to :

@Mapping(source = "healthCheck.bird.name", target = "name")
@Mapping(source = "healthCheck.id", target = "id")
@Mapping(source = "healthCheck.location.x", target = "latitude")
@Mapping(source = "healthCheck.location.y", target = "longitude")
HealthCheckViewDTO healthCheckToHealthCheckViewDTO(HealthCheck healthCheck, Transmitter transmitter);

Upvotes: 1

Related Questions