When you call cartRepository.deleteById(id):
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.