I have a ShoppingCart which has a set of CartItem objects .When I save the shoppingcart,all the cartitems are also saved.When the buyer confirms a buy,I need to clear the shoppingcart.If I save the cart to the db now,what should happen to the cartitems already saved in the db and associated with the cart?Should I remove them from db?
The jpa mappings of Entities are
@Entity
class ShoppingCart{
...
@OneToOne
public Buyer buyer;
@OneToMany(mappedBy="cart", cascade=CascadeType.ALL)
public Set<CartItem> cartItems;
...
}
@Entity
public class CartItem{
@ManyToOne
public ShoppingCart cart;
@OneToOne
public Product pdt;
public int quantity;
...
}
}
the shoppingcart table in db
id | buyer_id
-----+-------------
100 | 50
cartitem table can be
id | quantity | product_id | cart_id
-----+----------+------------+---------
12 | 2 | 234 | 100
--------------------------------------
13 | 4 | 231 | 100
So after I clear the shoppingcart and save it to db,if these items are still in db,it would mean that cartitem 12 still refers to cart 100.But ,cart with id=100 has no cartitems since I have cleared them.
So,is clearing a cart and saving it to db equivalent to deleting the cart?
How do I map this behaviour?Or is there a flaw in my thinking?
You haven’t posted code on how you are clearing the shopping cart, so my answer will make a fair number of assumptions.
Going by the contents of the tables, I’ll assume that you’ve invoked
cartItems.clear()in yourShoppingCartclass. The problem with this invocation is that your relationship is bidirectional and therefore aCartIteminstance will continue to have a reference back to theShoppingCartinstance, although the opposite isn’t true. Depending on what JPA provider you are using, clearing theSetand updating the persistence context contents with the database will either not clear thecartitemtable or will throw an exception stating that thecart_idcannot be null (if your foreign keys are not nullable).The fix in most JPA providers (especially in Hibernate) is to clear the reference to the
ShoppingCartin theCartIteminstance in addition to thecartItemsSet inShoppingCart. Note that, if you choose to deleted orphaned entries using theorphanRemovalattribute of the@OneToManyannotation (supported since JPA 2.0), then all orphanedCartItems(that are not referenced by aShoppingCart) will also be deleted in the database, on clearing the bidirectional relationship. Without theorphanRemovalattribute set to true, your JPA provider will make no attempt to deleteCartItems that are no longer referenced by aShoppingCart; the transaction will eventually be successful depending on whether your foreign key in the cartitem table is nullable or not.If you intend to retain the
CartItemrecords in the database, but merely nullify the reference to theShoppingCart, then you ought to designate the reference as nullable (using the@Columnannotation, and also have the table defined to have a nullable foreign key).