地图列表<字符串>使用 Mapstruct 从 Java POJO 到 Protobuf (proto3) [英] Map List&lt;String&gt; with Mapstruct from Java POJO to Protobuf (proto3)

查看:155
本文介绍了地图列表<字符串>使用 Mapstruct 从 Java POJO 到 Protobuf (proto3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些 POJO 从 Java 映射到 Protobuf (proto3).其中一些包含列表.虽然使用 POJO 映射列表(例如 List)没有问题,但我收到了 UnsupportedOperationException.

I'm trying to map some POJOs from Java to Protobuf (proto3). Some of them contain Lists. While mapping lists with POJOs (for example List) is no problem, I'm getting a UnsupportedOperationException.

List 的示例(这正确地工作):

Example with List<Product> (this works corrctly):

ProductProtobuf.Builder map(Product product);

@Mapping(target = "productsList", source = "products")
ResponseProtobuf.Builder map(Response response);

List 示例(这不起作用):

Example with List<String> (this doesn't work):

@Mapping(target = "usersList", source = "users")
ResponseProtobuf.Builder map(Response response);

此外,我有一些用于构建器的映射器:

Additionally, I have some Mapper for builder:

public ResponseProtobuf.Builder responseBuilder() {
    return ResponseProtobuf.newBuilder();
}

public ProductProtobuf build(ProductProtobuf.Builder builder) {
    return builder.build();
}

推荐答案

问题是 MapStruct 将使用 getProductsList().addAll().为了避免这种情况,您应该使用 CollectionMappingStrategy.ADDER_PREFERRED collectionMappingStrategy.看看 UserMapper 来自 mapstruct-protobuf3 在 mapstruct 示例存储库中.

The problem is that MapStruct will use getProductsList().addAll(). In order to avoid this you should use CollectionMappingStrategy.ADDER_PREFERRED collectionMappingStrategy. Have a look at the UserMapper from the mapstruct-protobuf3 in the mapstruct examples repo.

简而言之,您需要添加:

In a nutshell you need to add:

@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED,
    nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)

到您的映射器.

关于您的构建器的一个信息,如果您使用的是 1.3.0.Beta1,您将不需要它,因为现在 MapStruct 中提供了开箱即用的支持.

One information regarding your builder, in case you are using 1.3.0.Beta1 you won't need it as there is out of the box support for that in MapStruct now.

注意:MapStruct 中存在一个错误,无法与 <代码>ProtocolStringList.此错误已在 1.3.0.Beta1 中修复.如果您尝试使用此版本,它应该可以工作(如果您的 productListString)

NB: There was a bug in MapStruct that was not working correctly with ProtocolStringList. This bug has been fixed in 1.3.0.Beta1. If you try with this version it should work (in case your productList is a String)

这篇关于地图列表<字符串>使用 Mapstruct 从 Java POJO 到 Protobuf (proto3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆