gpt4 book ai didi

java - 将对象转换为 Long 时使用 mapstruct 取消映射目标属性

转载 作者:行者123 更新时间:2023-12-02 09:15:48 26 4
gpt4 key购买 nike

我在将对象转换为 Long 时遇到映射结构问题,出现以下警告:

警告:未映射的目标属性

以下是实体(我使用 Lombok):

    @Getter
@Setter
@NoArgsConstructor
@Entity
public class User {
...
private Set<Address> addresses= new HashSet<>();
...
}

@Getter
@Setter
@NoArgsConstructor
@Entity
public class Address {
...
private Town town;
...
}

@Getter
@Setter
@NoArgsConstructor
@Entity
public class Town {
...
private Long id;
...
}

和 DTO:

    @Getter
@Setter
@NoArgsConstructor
public class UserDTO {
...
private Set<AddressDTO> addresses= new HashSet<>();
...
}

@Getter
@Setter
@NoArgsConstructor
public class AddressDTO {
...
private Long townId;
...
}

在addressDTO中,我想要townId而不是城镇对象。以下是映射器:

@Mapper
public interface UserMapper {

UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);

UserDTO userToUserDTO(User user);

}

@Mapper
public interface AddressMapper {

AddressMapper INSTANCE = Mappers.getMapper(AddressMapper.class);

@Mapping(target = "townId", source = "town")
AddressDTO addressToAddressDTO(Address address);

default Long getTownId(Town town) {
return town.getId();
}
}

我为 AddressMapper 编写了一个有效的单元测试:

AddressDTO addressDTO = AddressMapper.INSTANCE.addressToAddresslDTO( address);

但它不适用于 UserMapper :

UserDTO userDTO = userMapper.INSTANCE.userToUserDTO( user);

我收到以下警告:

warning: Unmapped target property: "townId". Mapping from Collection element "fr.example.myproj.entity.Adress adresses" to "fr.example.myproj.service.dto.AdressDTO adresses".
UserDTO userToUserDTO(User user);

最佳答案

为了能够在UserMapper中重用AddressMapper,您可以使用Mapping#uses。这样 MapStruct 就会自动检测到 AddressMapper#addressToAddressDTO 方法。

例如

@Mapper(uses = AddressMapper.class)
public interface UserMapper {

UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);

UserDTO userToUserDTO(User user);

}

关于java - 将对象转换为 Long 时使用 mapstruct 取消映射目标属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58999202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com