【发布时间】:2020-11-17 16:33:11
【问题描述】:
大家好。 我想将 Point 作为字段的类陷入问题,我想将其转换为 DTO 字段。 我的实体和 DTO:
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class RentPointDto {
private String id;
private String pointName;
private String type;
private String coordinate;
}
public class RentPoint {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull(message = "Rent point name should'not be null")
@Column(name = "point_name")
private String pointName;
@Enumerated(EnumType.STRING)
private PointType type;
@Column(name = "coordinate")
@NotNull(message = "Coordinate of renting point must be specified!")
private Point coordinate;
(为简洁起见省略了一堆东西)
我的映射器:
public interface GenericMapper<S, DTO> {
DTO toDto(S s);
S fromDto(DTO dto);
List <S> listFromDto(List <DTO> dto);
List <DTO> listToDto(List <S> entities);
}
@Mapper(componentModel = "spring", uses = GeometryConverter.class)
public interface RentPointMapper extends GenericMapper <RentPoint, RentPointDto> {
}
和转换器类:
@Component
public class GeometryConverter {
public Point unMap(String str) throws ParseException {
return (Point) new WKTReader().read( str );
}
public String map(Point point) {
return point.toText();
}
}
为 Mapper 生成的 Impl:
@Autowired
private GeometryConverter geometryConverter;
@Override
public RentPointDto toDto(RentPoint s) {
if ( s == null ) {
return null;
}
RentPointDto rentPointDto = new RentPointDto();
if ( s.getId() != null ) {
rentPointDto.setId( String.valueOf( s.getId() ) );
}
rentPointDto.setPointName( s.getPointName() );
if ( s.getType() != null ) {
rentPointDto.setType( s.getType().name() );
}
rentPointDto.setCoordinate( geometryConverter.map( s.getCoordinate() ) );
return rentPointDto;
}
@Override
public RentPoint fromDto(RentPointDto dto) {
if ( dto == null ) {
return null;
}
RentPoint rentPoint = new RentPoint();
if ( dto.getId() != null ) {
rentPoint.setId( Long.parseLong( dto.getId() ) );
}
rentPoint.setPointName( dto.getPointName() );
if ( dto.getType() != null ) {
rentPoint.setType( Enum.valueOf( PointType.class, dto.getType() ) );
}
try {
rentPoint.setCoordinate( geometryConverter.unMap( dto.getCoordinate() ) );
}
catch ( ParseException e ) {
throw new RuntimeException( e );
}
return rentPoint;
}
毕竟,我得到了:
java:无法将属性“PointrentPoint.coordinate”映射到“String rentPoint.coordinate”。考虑声明/实现一个映射方法: “字符串映射(点值)”。
【问题讨论】:
标签: mapstruct