Я добавил скриншот результатов, которые дают конечные точки.
Пока что мой код:
Класс аккаунта:
Код: Выделить всё
@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 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 getAllCarts() {
return cartService.getCarts();
}
@GetMapping("/{id}")
public Cart getCartById(@PathVariable Long id) {
return cartService.getCartById(id);
}
@PutMapping("/add/{id}")
public ResponseEntity addItemsToCart(@PathVariable Long id, @RequestBody List items) {
if (cartService.updateCartContents(id, items)) {
return ResponseEntity.status(HttpStatus.OK).build();
} else {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity 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 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 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 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 getCarts(){
return cartRepository.findAll();
}
public Cart getCartById(Long id){
return cartRepository.findById(id).orElseThrow();
}
public boolean updateCartContents(Long id, List items){
Optional 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);
}
}
Вывод журналов консоли следующий:
`элементы корзины перед сохранением: [Item{id=1,createOn=2024-05-05T12:49:57.343516400,lastUpdateOn=null,cart=null,game=null, количество=null}, Item{id=2,createOn= 2024-05-05T12:49:57.344485400,lastUpdateOn=null,cart=null,game=null,количество=null}, Item{id=3,createOn=2024-05-05T12:49:57.344485400,lastUpdateOn=null, корзина =null, game=null, Quantity=null}]
предметы корзины после сохранения: [Item{id=1,createOn=2024-05-05T12:49:53.806481,lastUpdateOn=null , cart=null, game=com.united.Gamestore.Game.Game@2f5cee8, количество=1}, Item{id=2, CreateOn=2024-05-05T12:49:53.809481, LastUpdateOn=null, cars=null, game=com.united.Gamestore.Game.Game@7cedf75c, количество=1}, Item{id=3, CreateOn=2024-05-05T12:49:53.811481, LastUpdateOn=null, cars=null, game=com.united .Gamestore.Game.Game@6f5d6a00, количество=1}]`
Подробнее здесь: https://stackoverflow.com/questions/784 ... able-to-sa