首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MapStruct嵌套映射

MapStruct嵌套映射
EN

Stack Overflow用户
提问于 2020-07-23 01:45:36
回答 1查看 709关注 0票数 1

我需要将来自第三方API的响应映射到另一个响应结构。我使用Mapstruct来实现这一点。

ThirdParty应用编程接口类:

代码语言:javascript
复制
public class TPResponse {
     protected UserListsType userLists;
     protected ProductOffers offers;
     //getters and setters
}

public class UserListsType {
    protected UserTypes userTypes;
    ...............
}

public class UserTypes{
    protected List<User> userType;
}

public class User{
 protected String userID;
}

public class ProductOffers {
    protected List<OffersType> OffersType;
}

public class OffersType{
   protected PriceType totalPrice;
}

我们的API类:

代码语言:javascript
复制
public class ActualResponse {
       private List<Customer> user = new ArrayList<Customer>();
       //getters and setters
    }

  public class Customer{
        private String customerId;
        private String pdtPrice;
        private OfferPrice offerPrice;
    }
   public class OfferPrice{
        private String offerId;
  }

我想使用MapStruct来映射这些元素。

代码语言:javascript
复制
1) customerId <Map with> UserTypes->User->userID
2) pdtPrice  <Map with>  offers -> OffersType -> totalPrice
3) offerId  <Map with> sum of (offers -> OffersType -> totalPrice)

我尝试使用MapStruct编写映射器类,如下所示:

代码语言:javascript
复制
@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface UserResponseMapper {
    UserResponseMapper RESPONSE_MAPPER = Mappers.getMapper(UserResponseMapper.class);

    @Mappings({
            @Mapping(target="customer.customerId", source="userTypes.userType.userId")
    })
    ActualResponse mapUser(UserListsType userListType);

}

目前它显示的错误像“未知属性”、"customer.customerId“和"userTypes.userType.userId”。有人能帮我用Mapstruct映射所有这些元素吗?

问题2:我们如何映射以下内容? 1) customerId用户类型->用户->用户of 2) pdtPrice offers -> OffersType -> totalPrice 3) offerId sum of (offers -> OffersType -> totalPrice)

我试过了

代码语言:javascript
复制
@Mapping(target = "customerId", source = "userId")
@Mapping(target = "pdtPrice", source = "totalPrice")
    User mapUser(UserListsType userListType, OffersType offersType );

我得到了customerId和pdtPrice的空值

EN

回答 1

Stack Overflow用户

发布于 2020-07-23 14:22:52

据我所知,您需要映射ActualResponseUserTypeListType中的列表。

当您提供某些对象之间的映射时,MapStruct可以自动生成其集合之间的映射。因此,在您的情况下,您需要执行以下操作:

代码语言:javascript
复制
@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface UserResponseMapper {
    UserResponseMapper RESPONSE_MAPPER = Mappers.getMapper(UserResponseMapper.class);

    @Mappings({
            @Mapping(target="user", source="userType")
    })
    ActualResponse mapUser(UserTypeListType userListType);

    @Mapping(target = "customerId", source = "userId")
    User mapUser(UserType userType);

}

如果您需要进行计算,并且具有来自不同级别的对象,并且需要进行一些分组和/或聚合,我建议您编写自己的逻辑。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63040246

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档