Home > Enterprise >  How to remove data in spring boot
How to remove data in spring boot

Time:07-30

I am working on a sort of an e-commerce app with Java Spring boot,I have stored each user's product in a cart table and I want to implement it in a way that when a product is being delivered, that product should be removed from the cart table and stored in the shopping list table. Here is the code to perform the task for me. The error am getting is that when i pass the product id and the user authentication key, the message that I implemented "the product has been removed is returned successfully and the product is being stored in the shopping list table but not being removed from the cart table.

my cart class


@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Cart {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private Date createdDate;
    @ManyToOne
    @JoinColumn(name = "product_id")
    private Product product;
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;
    private int quantity;
}

shopping list class

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class ShoppingList {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private Date createdDate;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "cart_id")
    private Cart cart;
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User user;
    private String status;
}

cart repository

@Repository
public interface CartRepository extends JpaRepository<Cart,Integer> {

    List<Cart> findAllByUserOrderByCreatedDateDesc(User user);
}
shopping list repository

@Repository
public interface ShoppingListRepository extends JpaRepository<ShoppingList,Integer> {

    List<ShoppingList> findAllByUserOrderByCreatedDateDesc(User user);
}

Cart service

@Service
public class CartService {

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private ProductService productService;
    @Autowired
    private ShoppingListService shoppingListService;

    public void addToCart(AddToCartDto addToCartDto, User user) throws DataNotFoundException {

        Product product = productService.findById(addToCartDto.getProductId());
        Cart cart = new Cart();
        cart.setCreatedDate(new Date());
        cart.setProduct(product);
        cart.setUser(user);
        cart.setQuantity(addToCartDto.getQuantity());
        cartRepository.save(cart);

public void deleteCartItemByAdmin(Integer cartItemId, User user) throws DataNotFoundException {
        Optional<Cart> optionalCart = cartRepository.findById(cartItemId);
        if (optionalCart.isEmpty()){
            throw new DataNotFoundException("Item Id Not Found");
        }
        Cart cart = optionalCart.get();
        if (cart.getUser()!=user){
            throw new DataNotFoundException("The Item doesn't belongs to this user");
        }
        ShoppingList shoppingList = new ShoppingList();
        shoppingList.setCart(cart);
        shoppingList.setCreatedDate(new Date());
        shoppingList.setUser(cart.getUser());
        shoppingList.setStatus("Delivered");
        //In this case the admin want to delete the item that
        shoppingListService.addToShoppingList(shoppingList);
        cartRepository.delete(cart);
    }

    }

shopping list service

@Service
public class ShoppingListService {

    @Autowired
    private ShoppingListRepository shoppingListRepository;


    public void addToShoppingList(ShoppingList shoppingList){
        shoppingListRepository.save(shoppingList);
    }

this is my cart controller

    @DeleteMapping("/delete/by/admin/{itemId}")
    public ResponseEntity<ApiResponse> deleteItemByAdmin(@PathVariable("itemId")Integer itemId,
                                                  @RequestParam("token") String token) throws DataNotFoundException {
        authenticationTokenService.authenticateToken(token);
        User user = authenticationTokenService.getUserByToken(token);
        cartService.deleteCartItemByAdmin(itemId,user);
        return new ResponseEntity<>(new ApiResponse(true,"Item deleted Successfully from the Cart"),HttpStatus.OK);
    }
}

There is no need for me to paste my shopping list controller here because the add to shopping list is being called in the cart service whenever the admin want to remove an item from the cart.

Thanks for your helps

CodePudding user response:

Please,

  1. check if existes one id into the object (cart) in

"..cartRepository.delete(cart);.."

  1. After "...cart Repository.delete(cart); execute the command 'Flush' look like this "crudRepository.flush() or "

CodePudding user response:

you just pass your cart item id to delete.

public void deleteCartItemByAdmin(Integer cartItemId, User user) throws DataNotFoundException {
    Optional<Cart> optionalCart = cartRepository.findById(cartItemId);
    if (optionalCart.isEmpty()){
        throw new DataNotFoundException("Item Id Not Found");
    }
    Cart cart = optionalCart.get();
    if (cart.getUser()!=user){
        throw new DataNotFoundException("The Item doesn't belongs to this user");
    }
    ShoppingList shoppingList = new ShoppingList();
    shoppingList.setCart(cart);
    shoppingList.setCreatedDate(new Date());
    shoppingList.setUser(cart.getUser());
    shoppingList.setStatus("Delivered");
    //In this case the admin want to delete the item that
    shoppingListService.addToShoppingList(shoppingList);
    cartRepository.deleteById(cartItemId); // use like this
}

Thank you.

  • Related