【问题标题】:Ambiguous mapping methods using java Mapstruct使用 java Mapstruct 的模糊映射方法
【发布时间】:2019-02-09 18:23:40
【问题描述】:

我正在使用 java Mapstruct 将实体映射到 DTO

我想使用另一个映射器中的一个映射器,并且都使用相同的签名实现相同的方法,因此我得到“为映射属性找到不明确的映射方法”

我已经尝试在接口上实现共享方法,然后在两个映射器上扩展接口,但问题仍然存在

我猜我需要使用某种限定符。我在谷歌和官方文档中搜索过,但我不知道如何应用这个技术

// 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);
}
}

【问题讨论】:

    标签: java mapstruct


    【解决方案1】:

    使用限定符是解决此问题的一种方法。但是,在您的情况下,问题在于 fromInstant 方法,它实际上是一个 util 方法。

    为什么不将该方法提取到某个静态 util 类并告诉两个映射器也使用该类?

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

    那么您的映射器可能如下所示:

    @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);
    
    }
    

    【讨论】:

    • 这很棒。你的答案应该很明显,但今天是第一次接触这门课……非常感谢
    猜你喜欢
    • 2017-10-12
    • 2018-03-30
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2016-04-12
    相关资源
    最近更新 更多