3

Hi like in subject I would like to map entity class to DTO object.

Order Class:

@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;
}

Product class:

@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;
}

Order part class:

@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();
    }
}

At this moment im using mapper from 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);
}

And my DTO class

@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;
    }
}

I want to map this relation to my OrderDto object. Is there any way to map it automatically or I have to write my own mapper? Thanks for ur answers.

SergeiTonoian
  • 341
  • 2
  • 13
Oskar
  • 379
  • 4
  • 21

0 Answers0