我想映射这个 DTO :
public class BikeDTO {
private String wheel_1_color;
private String wheel_1_shape;
private String wheel_2_color;
private String wheel_2_shape;
}
致该实体:
public class BikeEntity {
private WheelEntity wheel1;
private WheelEntity wheel2;
}
public class WheelEntity {
private String color;
private String shape;
}
所以,我想知道是否可以只使用一个像这样的 WheelMapper :
@Mapper
public interface BikeMapper {
BikeMapper INSTANCE = Mappers.getMapper(BikeMapper.class);
@Mapping(target="wheel1", source=".", qualifiedByName ="dtoToWheel")
@Mapping(target="wheel2", source=".", qualifiedByName ="dtoToWheel")
BikeEntity dtoToEntity(BikeDTO dto);
@Named("dtoToWheel")
default WheelEntity dtoToWheel(BikeDTO dto) {
return WheelMapper.INSTANCE.dtoToWheel(dto);
}
}
@Mapper
public interface WheelMapper {
WheelMapper INSTANCE = Mappers.getMapper(WheelMapper.class);
@Mapping(target="color", source="wheel_" + wheelNumber + "_color")
@Mapping(target="shape", source="wheel_" + wheelNumber + "_shape")
WheelEntity dtoToWheel(BikeDTO dto);
}
我被
wheelNumber
困住了,不知道如何设置。
我编写了这段代码来表达我的需求,但我会采取任何对我有帮助的解决方案。
我可能想错了,我需要你的帮助?
PS:我显然无法更改我的 DTO 或实体的结构。
我认为在您的映射结构映射器中实现自定义映射函数会更容易。如果您不想使用 mapstruct 来实现这个简单的映射函数,您也可以将其导出到普通类或静态函数。因为您并没有真正使用任何映射结构功能,但它更容易且更具可读性:)
@Mapper
public interface BikeMapper {
default BikeEntity dtoToEntity(BikeDTO dto) {
return new BikeEntity(
new WheelEntity(dto.getWheel_1_Color(), dto.getWheel_1_Shape()),
new WheelEntity(dto.getWheel_2_Color(), dto.getWheel_2_Shape())
);
}
}
// easiest way would be to use lombok or define an all args contructor for each of those two entities
@AllArgsContructor
public class BikeEntity {
private WheelEntity wheel1;
private WheelEntity wheel2;
}
@AllArgsContructor
public class WheelEntity {
private String color;
private String shape;
}
如果您想使用mapstructs codegen,您可以在@Mapping中使用表达式,如下所示。多一点代码,不需要通过 mapstruct 生成它。在这两种解决方案中,如果自行车现在有 3 个轮子,则您必须调整映射器。所以你自己决定吧:D
@Mapper
public interface BikeMapper {
BikeMapper INSTANCE = Mappers.getMapper(BikeMapper.class);
@Mapping(target = "wheel1", expression = "java(WheelMapper.INSTANCE.dtoToWheel1(dto))")
@Mapping(target = "wheel2", expression = "java(WheelMapper.INSTANCE.dtoToWheel2(dto))")
BikeEntity dtoToEntity(BikeDTO dto);
}
@Mapper
public interface WheelMapper {
WheelMapper INSTANCE = Mappers.getMapper(WheelMapper.class);
@Mapping(target = "color", source = "wheel_1_color")
@Mapping(target = "shape", source = "wheel_1_shape")
WheelEntity dtoToWheel1(BikeDTO dto);
@Mapping(target = "color", source = "wheel_2_color")
@Mapping(target = "shape", source = "wheel_2_shape")
WheelEntity dtoToWheel2(BikeDTO dto);
}