在将对象转换为Long时,mapstruct存在问题,我有以下警告:
warning: Unmapped target property
以下是实体(我使用龙目岛):
@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而不是town对象。这是映射器:
@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);
答案 0 :(得分:1)
为了能够在AddressMapper
中重用UserMapper
,可以使用Mapping#uses
。这样AddressMapper#addressToAddressDTO
方法将被MapStruct自动检测。
例如
@Mapper(uses = AddressMapper.class)
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
UserDTO userToUserDTO(User user);
}
答案 1 :(得分:0)
我找到了使用custom method to mapper的解决方案。
@Mapper
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
UserDTO userToUserDTO(User user);
default AddressDTO addressToAddressDTO(Address address) {
return AddressMapper.INSTANCE.addressToAdressDTO( address );
}
}