开发者

lifespan relations of cartitem and Invoice.. doubts implementing shoppingcart

I am trying to implement a shopping cart web app like most newbies to javaee & hibernate..I went through many textbooks an开发者_开发知识库d still have doubts. I am hoping somebody here can help me correct my thinking.

I implemented a Product class and a CartItem. A CartItem has a Product field and a quantity field. When user wants to buy a Product,he adds a CartItem to the cart.

To model the user's buy, I wrote an Invoice class with a set of CartItem objects. It also has a customer field. Now, I am a bit confused about the corresponding tables and how their lifetimes should relate.

After an Invoice record is created(when user buys some items), should the corresponding cartitems be kept in db? Or once a user buys the items, should the cartitem records be deleted?

If someone can shed light on these, it would be nice.

Thanks,

Mark

Source code:

class CartItem {
    private Long cartItem_id;
    private Product product;
    private int quantity;
...
}

class Invoice {
    private Long invoice_id;
    private Customer customer;
    private Set<CartItem> cartItems;
    private Date invoiceDate;
    private int invoiceNumber;
    private double totalAmount;
...
}

I created tables CARTITEM and INVOICE as below.

CREATE TABLE CARTITEM(
    CARTITEM_ID BIGINT NOT NULL PRIMARY KEY IDENTITY,
    QUANTITY INTEGER,
    PRODUCT_ID BIGINT,
    FOREIGN KEY(PRODUCT_ID) REFERENCES PRODUCT(PRODUCT_ID)
)

CREATE TABLE INVOICE(
    INVOICE_ID BIGINT NOT NULL PRIMARY KEY IDENTITY,
    INVOICE_NUMBER INTEGER,
    INVOICE_DATE DATE,
    TOTAL_AMOUNT DOUBLE,    
    CUSTOMER_ID BIGINT,
    UNIQUE(INVOICE_NUMBER),
    FOREIGN KEY(CUSTOMER_ID) REFERENCES CUSTOMER(CUSTOMER_ID)
)


After an Invoice record is created(when user buys some items), should the corresponding cartitems be kept in db?

It all depends on your business rules. Do you want to recover those informations in the future? Probably, I guess. Then they should be persistent.

If you don't want to persist them, there's no need to create a database table (unless you want some crash recovering). You can keep the CarItems in session (assuming it's an web app).


Well, if you're persisting the invoice, it only makes sense to persist the CartItems that made up the invoice. Otherwise, how would a user be able to come back later and reprint the invoice, for instance?

Add a foreign key to your CARTITEM table to tie it to an invoice and you're set.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜