在Java Web開發中,添加訂單和訂單明細是常見的需求,下面簡要介紹一下實現方法。
首先,我們需要定義訂單和訂單明細的Java Bean,包括屬性以及對應的get/set方法。例如:
public class Order { private long id; private String customerName; private Listdetails; //訂單明細 //get/set方法略 } public class OrderDetail { private long id; private long orderId; private String productName; private int quantity; private double price; //get/set方法略 }
接下來,我們需要在數據庫中創建訂單和訂單明細的表,并使用JDBC或MyBatis等框架進行操作。例如:
public class OrderDao { private DataSource dataSource; public void addOrder(Order order) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); String sql = "INSERT INTO orders (customer_name) VALUES (?)"; stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, order.getCustomerName()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if (rs.next()) { long orderId = rs.getLong(1); order.setId(orderId); for (OrderDetail detail : order.getDetails()) { String sql2 = "INSERT INTO order_details (order_id, product_name, quantity, price) VALUES (?, ?, ?, ?)"; stmt = conn.prepareStatement(sql2); stmt.setLong(1, orderId); stmt.setString(2, detail.getProductName()); stmt.setInt(3, detail.getQuantity()); stmt.setDouble(4, detail.getPrice()); stmt.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); } finally { //釋放資源 } } }
上面代碼中,我們首先添加訂單,獲取生成的訂單ID,然后遍歷訂單明細列表,逐個添加。在添加時需要使用訂單ID作為外鍵與訂單建立關聯。
使用上述代碼即可完成Java添加訂單和訂單明細操作。