Skip to content

DataIntegrityViolationException #4

Description

@yaeby
  1. If you try to delete a product which key is present in order_item or cart_item then a DataIntegrityViolationException happens.
    Thus, there should be added a deletion logic to first delete the orderItems/cartItems then the product, or to set product's key in that tabels to null.

"message": "could not execute statement [Cannot delete or update a parent row: a foreign key constraint fails...

  1. Another issue is the clearCart method (this one does not throw error):
@Transactional
    @Override
    public void clearCart(Long id) {
        Cart cart = getCart(id);
        cartItemRepository.deleteAllByCartId(id);
        cart.clearCart();
        cartRepository.delete(cart);
    }

here the cart row will not be deleted from the table because the User entity has a bi-directional @OnetoOne relationship with Cart, thus when you call cartRepository.delete(cart):

  • The User entity still references the Cart.
  • Hibernate does not break the relationship between User and Cart.
  • Since the User is the owner of the relationship, the Cart is not fully deleted.

To fix this, you must update the User's reference to null before deleting the Cart.

@Transactional
    @Override
    public void clearCart(Long id) {
        Cart cart = getCart(id);
        cartItemRepository.deleteAllByCartId(id);

        // Break the relationship
        User user = cart.getUser();
        if (user != null) {
            user.setCart(null); // Detach the Cart from User
        }

        cart.clearCart();
        cartRepository.delete(cart);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions