如何在将父实体保存到数据库的同时保存子实体?

How can i save the child entity while saving the parent entity to the database?

我正在尝试开发一个小型电子商务项目。 我有一个 Basket 和 BasketItem 实体。 我只是想当我为客户保存购物篮时,我希望将购物篮项目保存在 database.I 认为我不应该为购物篮创建存储库 item.I 应该能够保存购物篮项目同时使用篮子存储库保存篮子。

public class Basket extends BaseModel {

    @Column(nullable = false)
    private BigDecimal price;

    private BigDecimal discountPrice = BigDecimal.ZERO;
    private BigDecimal taxPrice = BigDecimal.ZERO;
    private BigDecimal shippingPrice = BigDecimal.ZERO;

    @Column(nullable = false)
    private BigDecimal totalPrice;

    @OneToMany(mappedBy = "basket", cascade = CascadeType.PERSIST)
    private Set<BasketItem> items = new HashSet<>();

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "customer_id", nullable = false)
    private Customer customer;

}
public class BasketItem extends BaseModel {

    @ManyToOne(optional = false)
    private Basket basket;

    @ManyToOne(optional = false)
    private Product product;

    @Column(nullable = false)
    private Long quantity;
    @Column(nullable = false)
    private BigDecimal price = BigDecimal.ZERO;
    private BigDecimal discountPrice = BigDecimal.ZERO;
    private BigDecimal taxPrice = BigDecimal.ZERO;
    private BigDecimal shippingPrice = BigDecimal.ZERO;
}

我在这里尝试通过购物车服务获取购物车商品并将其设置为购物车实体并保存。

public class BasketServiceImpl implements BasketService{

    private final CustomerRepository customerRepository;
    private final BasketRepository basketRepository;
    private final BasketItemConverter basketItemConverter;

    @Override
    public void addBasketItemToBasket(Long customerId, AddBasketItemDTO addBasketItemDTO) {
        //Find customer
        Customer customer = customerRepository.findById(customerId).orElseThrow(
                () -> new BusinessServiceOperationException.CustomerNotFoundException("Customer not found")
        );
        //Convert AddBasketItemDto to BasketItem
        BasketItem basketItem = basketItemConverter.toBasketItem(addBasketItemDTO);
        Set<BasketItem> basketItemsList = new HashSet<BasketItem>();
        Basket basket = new Basket();
        basketItemsList.add(basketItem);

        basket.setItems(basketItemsList);
        basket.setCustomer(customer);
        basket.setPrice(BigDecimal.ZERO);
        basket.setTotalPrice(BigDecimal.ZERO);
        basketRepository.save(basket);
    }
}

我的问题是什么?我得到了这个例外。

{
    "errorMessage": "detached entity passed to persist: org.patikadev.orderexample.model.BasketItem; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: org.patikadev.orderexample.model.BasketItem"
}

是的,如果购物篮具有适当的持久链接,则您不需要购物篮项目存储库。但是您必须先保存 Item,然后将其添加到篮子并在最后保存篮子。