Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous mapping methods using java Mapstruct

Tags:

java

mapstruct

I'm working with java Mapstruct to mapping Entities to DTOs

I want to use one mapper from other mapper and both implement the same method with the same signature and because of that I'm getting "Ambiguous mapping methods found for mapping property"

I have already tried to implement the shared method on an interface and then extend the interface on both mappers but the problem remains

I'm guessing I will need to use some kind of qualifier. I searched on google and in the official documentation but I can't figure it out how to apply this technic

// CHILD MAPPER ***
@Mapper(componentModel = "spring", uses = { })
public interface CustomerTagApiMapper {

CustomerTagAPI toCustomerTagApi(CustomerTag customerTag);

default OffsetDateTime fromInstant(Instant instant) {
    return instant == null ? null : instant.atOffset(ZoneOffset.UTC);
}
} 

// PARENT MAPPER ***
@Mapper(componentModel = "spring", uses = {  CustomerTagApiMapper.class })
public interface CustomerApiMapper {

CustomerAPI toCustomerApi(Customer customer);

default OffsetDateTime frmInstant(Instant instant) {
    return instant == null ? null : instant.atOffset(ZoneOffset.UTC);
}
}
like image 635
Bruno Miguel Avatar asked Jan 24 '26 03:01

Bruno Miguel


1 Answers

Using a qualifier is one way to solve this. However, in your case the problem is the fromInstant method which is actually an util method.

Why don't you extract that method to some static util class and tell both mapper to use that class as well?

public class MapperUtils {

    public static OffsetDateTime fromInstant(Instant instant) {
        return instant == null ? null : instant.atOffset(ZoneOffset.UTC);
    }
}

Then your mappers can look like:

@Mapper(componentModel = "spring", uses = { MapperUtils.class })
public interface CustomerTagApiMapper {

    CustomerTagAPI toCustomerTagApi(CustomerTag customerTag);

}

@Mapper(componentModel = "spring", uses = {  CustomerTagApiMapper.class, MapperUtils.class })
public interface CustomerApiMapper {

    CustomerAPI toCustomerApi(Customer customer);

}
like image 51
Filip Avatar answered Jan 26 '26 16:01

Filip



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!