我需要一些社区帮助来指出我在我的代码中出错的地方......:)
我尝试使用mapstruct在@ObjectFactory的帮助下映射2个实体之间的字段。
实体1:
public class ScimUser {
@JsonProperty("addresses")
@Valid
private List<UserAddress> addresses = null;
}
实体2:
public class User {
@JsonProperty("postalAddress")
private PostalAddress postalAddress = null;
}
映射器:
@Mapper(componentModel = "spring", uses = { AddressFactory.class })
public interface ScimUserMapper {
@Mapping(target = "postalAddress", source = "scimUser.addresses")
User toUser(ScimUser scimUser);
@Mapping(target = "addresses", source = "user.postalAddress")
ScimUser toScimUser(User user);
}
的ObjectFactory:
@Component
public class AddressFactory {
@Autowired
private CountryMapper countryMapper;
@Autowired
private CountryRepository countryRepository;
@ObjectFactory
public PostalAddress toPostalAddress(List<UserAddress> addresses, @TargetType Class<PostalAddress> type) {
PostalAddress postalAddress = new PostalAddress();
if (addresses != null && !addresses.isEmpty()) {
UserAddress userAddress = addresses.stream().filter(UserAddress::isPrimary).findFirst().orElse(null);
if (userAddress == null) {
userAddress = addresses.get(0);
}
postalAddress.setAddressLine1(userAddress.getStreetAddress());
postalAddress.setPostCode(userAddress.getPostalCode());
postalAddress.setState(userAddress.getRegion());
postalAddress.setCity(userAddress.getLocality());
CountryJpa countryJpa = countryRepository.getCountryByIso2Code(userAddress.getCountry());
if (countryJpa != null) {
Country country = countryMapper.fromJPA(countryJpa);
postalAddress.setCountry(country);
}
}
return postalAddress;
}
@ObjectFactory
public List<UserAddress> toUserAddressList(PostalAddress address, @TargetType Class<List<UserAddress>> type) {
UserAddress userAddress = new UserAddress();
userAddress.setCountry(address.getCountry().getIso2());
userAddress.setFormatted("?");
userAddress.setLocality(address.getCity());
userAddress.setPostalCode(address.getPostCode());
userAddress.setPrimary(true);
userAddress.setRegion(address.getState());
userAddress.setStreetAddress(address.getAddressLine1());
userAddress.setType("?");
return Collections.singletonList(userAddress);
}
}
上面的代码在源代码生成过程中遇到了这个错误:
无法将属性“java.util.List addresses”映射到“PostalAddress postalAddress”。考虑声明/实现映射方法:“PostalAddress map(java.util.List value)”。 无法将属性“PostalAddress postalAddress”映射到“java.util.List addresses”。考虑声明/实现一个映射方法:“java.util.List map(PostalAddress value)”。
这不是我第一次使用这些对象工厂,我真的不知道我做错了什么。
所以如果有人有想法,我会很高兴看到它。 :)
答案 0 :(得分:1)
您使用的是@ObjectFactory
错误。你想要实现的是一种自定义映射方法。
@ObjectFactory
需要用于创建目标实例对象。在您的情况下,如果您只是从方法中删除@ObjectFactory
和@TargetType
,那么它应该可以正常工作。
我必须强调你在那里进行了一些手动映射。您可以轻松地提供单个UserAddress
和PostalAddress
之间的映射方法,并只为集合添加包装器。