79807000

Date: 2025-11-02 08:03:00
Score: 0.5
Natty:
Report link

When you call cartRepository.deleteById(id):

  1. The Cart entity is deleted from the database.
  2. The CartItem entities are deleted (due to CascadeType.ALL and orphanRemoval = true on the Cart's items field).
  3. The User object, which is currently a managed entity in the transaction, still holds a reference to the deleted Cart object in its cart field.
  4. When the @Transactional method clearCart finishes, the persistence context performs a flush. Because the User entity has cascade = CascadeType.ALL and orphanRemoval = true on its cart field, and the User still thinks that Cart exists (it's not null in its field), Hibernate might try to manage/re-save the detached or deleted Cart entity, causing the cleanup delay.

You will need to fetch the Cart, get its associated User, clear the reference, and then delete the Cart

    @Transactional
    @Override
    public void clearCart(Long id) {
        Cart cart = cartRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Cart not found for ID: " + id));
        User user = cart.getUser();
        if (user != null) {
            user.setCart(null);
            userRepository.save(user);
        }
        cartItemRepository.deleteByCartId(id);
        cartRepository.delete(cart);  
    }

After this method, the transaction commits, and both entities are fully detached.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Transactional
  • Starts with a question (0.5): When you
  • Low reputation (0.5):
Posted by: Max