我正在開發在線商店應用程式,但我正在努力使用購買系統。通常我需要撰寫與步驟一起使用的服務:
- 檢查客戶是否有足夠的資金支付
- 如果他這樣做了 - 從余額中減去產品
Customer成本 Product從集合中洗掉Customer(這不起作用!)- 將更新的集合保存
Customer到資料庫 Product從資料庫中洗掉
但是,無論我如何嘗試這樣做,都不會從集合中Product洗掉。方法,方法等,沒有任何作用。每次我在購買后將收藏登錄到控制臺,購買的仍然屬于發布者。這個主要問題會導致許多錯誤 - 例如 - 考慮保存不存在(因為在下次購買時,保存包括未洗掉的先前收藏)。Customerremove()clear()CustomerProductCustomerProductCustomerProductCustomerProductCustomer
代碼片段:
服務部分:
public boolean processPayment(Customer customerToEdit, Product productToOperate) {
if (customerToEdit.getBalance() >= productToOperate.getProductCost())
{
Customer retrievedProductOwner = productToOperate.getProductOwner();
customerToEdit.setBalance(customerToEdit.getBalance()-productToOperate.getProductCost());
/* This doesn't execute! */
retrievedProductOwner.getOwnedProducts().remove(productToOperate);
customerDAO.save(retrievedProductOwner);
}
else {
System.out.println("Insufficient funds!");
return false;
}
return true;
}
控制器:
@GetMapping("/showOffer")
public String getOffer(@RequestParam("offerId") int offerId, Model theModel, @AuthenticationPrincipal MyUserDetails user) {
Product retrievedProduct = productService.findById(offerId);
if (customerService.processPayment(user.getCustomer(), retrievedProduct)) {
productService.delete(retrievedProduct.getId());
}
return "redirect:/home";
}
產品.java:
@Entity
@Table(name="product")
public class Product {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="name")
private String productName;
@Column(name="description")
private String productDescription;
@Column(name="category")
private String productCategory;
@Column(name="cost")
private int productCost;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="owner_id")
private Customer productOwner;
/* (...) */
客戶.java:
@Entity
@Table(name="customer")
public class Customer {
//Class fields
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="balance")
private int balance;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="email")
private String email;
@OneToMany(mappedBy="productOwner", fetch=FetchType.EAGER)
private List<Product> ownedProducts;
/* (...) */
uj5u.com熱心網友回復:
您需要通過添加 CascadeType.PERSIST 和 orphan removal true 來啟用產品的孤立洗掉
@OneToMany(mappedBy = "productOwner", fetch = FetchType.EAGER, cascade = CascadeType.PERSIST, orphanRemoval = true)
private List<Product> ownedProducts = new ArrayList<>();
當您保存客戶時,這應該會觸發洗掉已洗掉產品
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/513225.html
