我正在尝试制作我的第一个 Spring Boot 应用程序,并且我想将项目列表添加到购物车。但由于某种原因,项目列表没有保存到数据库中。
我添加了端点产生的结果的屏幕截图。
到目前为止我的代码:
账户类别:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Account {
@GeneratedValue
@Id
private Long id;
@Column(nullable = false)
private String name;
@Column(unique = true, nullable = false)
private String email;
@Column(length = 1000, nullable = false)
private String password;
private LocalDateTime createdOn;
{
createdOn = LocalDateTime.now();
}
private LocalDateTime lastUpdateOn;
@JsonManagedReference
@OneToOne(cascade = CascadeType.PERSIST)
private Cart cart;
// Constructor for Seeder
public Account(String name, String email, String password) {
this.cart = new Cart();
this.name = name;
this.email = email;
this.password = password;
this.createdOn = LocalDateTime.now();
}
}
推车类:
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Cart {
@GeneratedValue
@Id
private Long id;
@JsonBackReference
@OneToOne
private Account account;
private LocalDateTime createdOn;
{
createdOn = LocalDateTime.now();
}
private LocalDateTime lastUpdateOn;
@JsonManagedReference
@OneToMany(mappedBy = "cart")
private List<Item> items;
private String test;
}
物品类别:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Item {
@GeneratedValue
@Id
private Long id;
private LocalDateTime createdOn;
{
createdOn = LocalDateTime.now();
}
private LocalDateTime lastUpdateOn;
@JsonBackReference
@ManyToOne
@JoinColumn(name = "cart_id")
private Cart cart;
@ManyToOne
@JoinColumn(name = "game_id")
private Game game;
private Integer quantity;
public Item(Game game, Integer quantity) {
this.game = game;
this.quantity = quantity;
}
}
推车控制器:
@RequestMapping("/carts")
@RestController
public class CartController {
@Autowired
CartService cartService;
@GetMapping
public List<Cart> getAllCarts() {
return cartService.getCarts();
}
@GetMapping("/{id}")
public Cart getCartById(@PathVariable Long id) {
return cartService.getCartById(id);
}
@PutMapping("/add/{id}")
public ResponseEntity<Cart> addItemsToCart(@PathVariable Long id, @RequestBody List<Item> items) {
if (cartService.updateCartContents(id, items)) {
return ResponseEntity.status(HttpStatus.OK).build();
} else {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Cart> deleteCart(@PathVariable Long id) {
if (cartService.deleteCart(id)) {
return ResponseEntity.status(HttpStatus.OK).build();
} else {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
}
@PutMapping("clearcart/{id}")
public ResponseEntity<Cart> clearCart(@PathVariable Long id){
if (cartService.clearCart(id)){
return ResponseEntity.status(HttpStatus.OK).build();
} else {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
}
@PutMapping("removeitem/{id}")
public ResponseEntity<Cart> removeCartItems(@PathVariable Long id, @RequestBody Item item){
if (cartService.removeCartItem(id,item)){
return ResponseEntity.status(HttpStatus.OK).build();
} else {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
}
// check out. dus zet cart om in purchase en clear de cart
@PutMapping("checkout/{id}")
public ResponseEntity<Cart> checkout(@PathVariable Long id){
try{
cartService.checkout(id);
return ResponseEntity.status(HttpStatus.OK).build();
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
}
}
和购物车服务:
@Service
public class CartService {
@Autowired
CartRepository cartRepository;
@Autowired
ItemRepository itemRepository;
@Autowired
PurchaseRepository purchaseRepository;
public List<Cart> getCarts(){
return cartRepository.findAll();
}
public Cart getCartById(Long id){
return cartRepository.findById(id).orElseThrow();
}
public boolean updateCartContents(Long id, List<Item> items){
Optional<Cart> optionalCart = cartRepository.findById(id);
if (optionalCart.isPresent()) {
Cart cart = optionalCart.get();
cart.getItems().addAll(items);
System.out.println("cart items before saving: " + cart.getItems());
cartRepository.save(cart);
System.out.println("cart items after saving: " + cart.getItems());
return true;
} else {
return false;
}
}
public boolean deleteCart(Long id){
if(cartRepository.findById(id).isPresent()){
cartRepository.deleteById(id);
return true;
}else{
return false;
}
}
public boolean clearCart(Long id){
if(cartRepository.findById(id).isPresent()){
Cart cart = cartRepository.findById(id).orElseThrow();
cart.getItems().clear();
cartRepository.save(cart);
return true;
}else{
return false;
}
}
public boolean removeCartItem(Long id, Item itemToRemove){
if(cartRepository.findById(id).isPresent()){
Cart cart = cartRepository.findById(id).orElseThrow();
cart.getItems().remove(itemRepository.findById(itemToRemove.getId()).orElseThrow());
cartRepository.save(cart);
return true;
}else{
return false;
}
}
public void checkout(Long id) throws IllegalArgumentException{
Cart cart = cartRepository.findById(id).orElseThrow(IllegalArgumentException::new);
//Purchase purchase = new Purchase();
//purchase.setPurchasedItems(cart.getItems());
//purchaseRepository.save(purchase);
clearCart(id);
}
}
我添加了一个名为 test 的字符串变量,以查看购物车是否根本没有更新,但是当我调整它时,它确实显示在购物车中。所以问题似乎特别出在项目列表上。我添加了一个控制台日志来调用该列表,并且在我的控制台中它确实记录了它,就像添加了项目一样。
控制台日志输出如下: `保存前的购物车项目:[Item{id=1,createdOn=2024-05-05T12:49:57.343516400,lastUpdateOn=null,cart=null,game=null,quantity=null},Item{id=2,createdOn= 2024-05-05T12:49:57.344485400,lastUpdateOn = null,购物车= null,游戏= null,数量= null},项目{id = 3,createdOn = 2024-05-05T12:49:57.344485400,lastUpdateOn = null,购物车=空,游戏=空,数量=空}]
保存后的购物车项目:[Item{id=1,createdOn=2024-05-05T12:49:53.806481,lastUpdateOn=null,cart=null,game=com.united.Gamestore.Game.Game@2f5cee8,quantity=1 },项目{id = 2,createdOn = 2024-05-05T12:49:53.809481,lastUpdateOn = null,cart = null,game = com.united.Gamestore.Game.Game@7cedf75c,数量= 1},项目{id =3、createdOn=2024-05-05T12:49:53.811481、lastUpdateOn=null、cart=null、game=com.united.Gamestore.Game.Game@6f5d6a00、数量=1}]`
您的多对一/一对多关系是双向的。当您向列表添加新条目时,您还必须在目标实体中设置引用。在购物车实体中实现一个辅助方法,如下所示:
public void addItem(Item item) {
items().add(item);
item.setCart(this);
}
与此类似,您应该实现一个删除条目的方法:
public void removeItem(Item item) {
items().remove(item);
item.setCart(null);
}
这样您就可以在一处实现,并且关系将正确同步。
基于:https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/