如何将DTO中的ID映射到实体上的类的ID

时间:2019-05-08 11:25:53

标签: java modelmapper

我正在尝试从ProductInviewDTO映射,该产品具有一个完整的产品ID,以链接到在ProductReview实体上找到的产品。但是,使用ModelMapper似乎无法正确映射。导致无法设置值的错误消息以及IllegalArgument异常,导致在尝试设置值时该对象不是声明类的实例,从而导致失败。

ProductReview到ProductReviewDTO的第一个映射工作正常。

DTO:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ProductReviewDTO {

    private int id;
    private int productId;
}

实体:

@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "product_reviews")
public class ProductReview {

    @Id
    @SequenceGenerator(name="product_reviews_generator", sequenceName = "product_reviews_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_reviews_generator")
    @Column(name = "id", updatable = false, nullable = false)
    private int id;

    @ManyToOne(cascade=CascadeType.DETACH, fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", nullable=false)
    private Product product;
}

映射:

@NoArgsConstructor
public class ProductReviewMapping implements BaseMapping<ProductReview, ProductReviewDTO> {

    @Override
    public PropertyMap<ProductReview, ProductReviewDTO> MapFromSourceToTarget() {
        return new PropertyMap<ProductReview, ProductReviewDTO>() {
            protected void configure() {
                map().setProductId(source.getProduct().getId());
                map().setUserId(source.getUser().getId());
                map().setRatingId(source.getRating().getId());
            }
        };
    }

    @Override
    public PropertyMap<ProductReviewDTO, ProductReview> MapFromTargetToSource() {
        return new PropertyMap<ProductReviewDTO, ProductReview>() {
            protected void configure() {
                map().setProduct(new Product().builder().id(source.getProductId()).build());
            }
        };
    }
}

Caused by: org.modelmapper.MappingException: ModelMapper mapping errors:

1) Failed to set value '1' on com.pfex.ecom.library.common.entity.Product$ProductBuilder.id()

0 个答案:

没有答案