'Confusing situation when registering the product
i have problem with my e-commerce app. I'm confused when saving the product entity. I have a Product,Brand and Category Model like this
@Getter
@Setter
@Entity
public class Product extends BaseExtendedModel {
private String name;
private BigDecimal price;
private UUID barcode;
private String image;
@ManyToOne
private Brand brand;
@ManyToOne
private Category category;
private int stock;
}
@Getter
@Setter
@Entity
public class Brand extends BaseModel {
private String name;
}
@Entity
@Getter
@Setter
public class Category extends BaseModel {
@OneToOne
private Category parent;
private String name;
}
I used CreateProductRequestDTO to save the data
public record CreateProductRequestDTO(String name, BigDecimal price, String image, Long brandId, Long categoryId, int stock) {
}
I got the necessary DTO information from the user to register product. And to save this information as product I need to convert DTO to product. And I'm doing this convert in the ProductConverterImpl below.
@Component
public class ProductConverterImpl implements ProductConverter{
@Override
public Product toProduct(CreateProductRequestDTO createProductRequestDTO) {
Product product = new Product();
product.setName(createProductRequestDTO.name());
product.setPrice(createProductRequestDTO.price());
product.setImage(createProductRequestDTO.image());
Brand brand = new Brand();
brand.setId(createProductRequestDTO.brandId());
Category category = new Category();
category.setId(createProductRequestDTO.categoryId());
product.setCategory(category);
product.setStock(createProductRequestDTO.stock());
product.setBrand(brand);
product.setCreatedBy("Yunus Emre");
return product;
}
}
But I am confused about this. Because in my product model i have brand,category model as property marked @ManyToOne. I don't have Brand and Category object that I can set during the convert process. I am only getting brandId and categoryId from user. How can I set this Product object with the brand and category fields set according to the id information I received from the user? I need help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
