我有一个DTO课程,正在扩展spring-hateoas
的ResourceSupport
课程。 UserMinimalDto
是User
实体的DTO。
因此,为了生成映射器类,我使用的是mapStruct。
@Data //from lambok
@EqualsAndHashCode(callSuper=false)
public class UserMinimalDto extends ResourceSupport {
String firstName;
String lastName;
String email;
String uniqueId;
String profilePicUrl;
}
我正在使用ResourceSupport
添加hateoas链接到控制器的响应。
Mapper界面
@Mapper
public interface UserMinimalMapper {
UserMinimalMapper INSTANCE = Mappers.getMapper(UserMinimalMapper.class) ;
UserMinimalDto entityToDto(User user);
User dtoToEntity(UserMinimalDto userMinimalDto);
}
但是当我在项目上运行mvn clean install
时,我面临编译错误
无法将属性“org.springframework.hateoas.Link id”映射到“java.lang.Integer id”。考虑声明/实现映射方法:“java.lang.Integer map(org.springframework.hateoas.Link value)”。
这是因为mapStruct
正在尝试ResourceSupport
的地图。它的工作如果:
告诉mapStruct
不映射超类字段的配置是什么?
为了忽略逐个案例的字段,您可以使用Mapping#ignore
。
在您的情况下,它看起来像:
@Mapper
public interface UserMinimalMapper {
UserMinimalMapper INSTANCE = Mappers.getMapper(UserMinimalMapper.class) ;
UserMinimalDto entityToDto(User user);
@Mapping(target = "id", ignore = true)
@Mapping(target = "links", ignore = true)
User dtoToEntity(UserMinimalDto userMinimalDto);
}
如果您的实体具有通用接口/类,则可以使用@MapperConfig
并定义这些排除项。
它看起来像:
@MapperConfig(mappingInheritanceStrategy = MappingInheritanceStrategy.AUTO_INHERIT_FROM_CONFIG)
public interface CommonMappingConfig {
@Mapping(target = "id", ignore = true)
@Mapping(target = "links", ignore = true)
BaseEntity map(ResourceSupport resourceSupport);
}
@Mapper(config = CommonMappingConfig.class)
public interface UserMinimalMapper {
UserMinimalMapper INSTANCE = Mappers.getMapper(UserMinimalMapper.class) ;
UserMinimalDto entityToDto(User user);
User dtoToEntity(UserMinimalDto userMinimalDto);
}
这是因为模型类具有除DTO
之外的其他字段集,并且您的映射器以两种方式映射。但这很自然,dto没有id。
解决方法是从映射中排除这些字段,例如通过注释id
和模型类中的其他字段,这些字段不在dto中:Mapping("this")
。