简体   繁体   中英

MYSQL : multiple table insert with foreign key relationship

Orders table


order_id,  
parent_order_id,  
customer_id,  
payment_mode, 
price ,
shipping_price, 
billing_address_id,  
shipping_address_id,  
create_TS,  
update_TS 

Order Items


order_id,
order_item_id, 
pos_code,  
quantity,  
unit_price, 
shipping_price, 
pickup_date,   
create_TS,   
update_TS,  
business_id,
item_id, 
delivery_id,  
workflow_id,

Order Adjustments Table


order_adjustment_id, 
order_item_id,  
offer_id,   
discount_value,  
create_ts, 
update_ts

When an order is placed, I insert data into these 3 tables plus a few other tables. All of them happen in a transaction. Currently the application uses JDBC to talk to the MYSQL DB.

The order of insertion is 1. Orders table. 2. OrderItems table 3. Order_Adjustments table

The order id is a foreign key in the order items table and order item id is a foreign key in the order adjustments table.

When a customer places an order I divide the Parent order into sub orders based on the stores. For example if the cart contains item1 and item2 from store1 item3 and item4 from store2

This single cart will be broken into 2 separate orders(due to logistics reasons)

So now the problem is,

I need to know the corresponding order id for the order items table and similarly the corresponding order item ids for order adjustments table.

Because of which I am firing queries separately instead of a bulk insert. Is it even possible to acheive something like this using jdbc?

You have to first fire query into 1. Orders table.

based upon it get MAX(order_id) from table Orders table , then use it for foreign key into other child tables.

You can also get the id like this. It will return the id created by the DB for your order.

p = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

After executeUpdate you can get the id like this.

ResultSet rs = p.getGeneratedKeys();
rs.getInt(1)

Now you can take the id and use it as a FK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM