嗨,就像主题一样,我想将实体类映射到 DTO 对象。
订单类别:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "ORDERS")
public class Order extends BaseEntity {
@Column(name = "ORDER_DATE")
private LocalDateTime orderDate;
@Column(name = "TOTAL_PRICE")
private double totalPrice;
@OneToMany(mappedBy = "order")
Set<OrderPart> orderParts;
}
产品类别:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "PRODUCT")
public class Product extends BaseEntity {
@Column(name = "NAME")
private String name;
@Column(name = "PRICE")
private double price;
@OneToMany(mappedBy = "product")
Set<OrderPart> orderParts;
}
订购零件类别:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "ORDER_PART")
public class OrderPart extends BaseEntity {
@Column(name = "QUANTITY")
private int quantity;
@ManyToOne
@JoinColumn(name = "ORDER_ID")
Order order;
@ManyToOne
@JoinColumn(name = "PRODUCT_ID")
Product product;
public double getPriceOfProduct() {
return product.getPrice();
}
}
此时我正在使用 mapstruct 中的映射器:
@Mapper(componentModel = "spring")
public interface WarehouseApiMapper {
WarehouseApiMapper mapper = Mappers.getMapper(WarehouseApiMapper.class);
@Mapping(target = "orderDate", dateFormat = "yyyy-MM-dd HH:mm")
OrderDto OrderToOrderDto(Order order);
}
还有我的 DTO 课
@Data
public class OrderDto {
private Integer id;
private String orderDate;
private Double totalPrice;
private Set<ProductDto> products;
public OrderDto(String orderDate, Double totalPrice) {
this.orderDate = orderDate;
this.totalPrice = totalPrice;
}
}
我想将此关系映射到我的 OrderDto 对象。有没有办法自动映射它或者我必须编写自己的映射器?感谢您的回答。