我正在嘗試開發一個迷你電子商務專案。我有一個 Basket 和 BasketItem 物體。我只想在為客戶保存籃子時,將籃子專案保存在資料庫中。我認為我不應該為籃子專案創建存盤庫。我應該能夠在保存籃子的同時保存籃子專案與籃子存盤庫。
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"
}
uj5u.com熱心網友回復:
是的,如果籃子具有適當的持久鏈接,則您不需要籃子專案存盤庫。但是您必須先保存專案,然后將其添加到籃子并在最后保存籃子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/467292.html
上一篇:一個簡單的HelloWorld應用程式SpringBoot上的Whitelabel錯誤
下一篇:為成功API回應添加攔截器
