69 lines
2.3 KiB
Java
69 lines
2.3 KiB
Java
package DAO;
|
|
|
|
import DTO.Order;
|
|
import DTO.OrderItem;
|
|
import util.DataSourceProvider;
|
|
|
|
import java.sql.Connection;
|
|
import java.sql.PreparedStatement;
|
|
import java.sql.ResultSet;
|
|
import java.sql.SQLException;
|
|
import java.util.LinkedList;
|
|
import java.util.List;
|
|
|
|
public class OrderItemDao {
|
|
|
|
public static List<OrderItem> getItemsForOrderId(int id) {
|
|
List<OrderItem> result = new LinkedList<>();
|
|
String sql = "select item_name, quantity, price from order_items where ORDER_ID=?";
|
|
try (Connection con = DataSourceProvider.getDataSource().getConnection();
|
|
PreparedStatement ps = con.prepareStatement(sql)) {
|
|
ps.setInt(1, id);
|
|
try(ResultSet rs = ps.executeQuery()) {
|
|
while (rs.next()) {
|
|
OrderItem item = new OrderItem();
|
|
item.setItemName(rs.getString(1));
|
|
item.setQuantity(rs.getInt(2));
|
|
item.setPrice(rs.getInt(3));
|
|
result.add(item);
|
|
}
|
|
}
|
|
|
|
} catch (SQLException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
public static void saveOrderItem(OrderItem item, int orderId) {
|
|
String sql = "insert into order_items (order_id, item_name, quantity, price) VALUES (?,?,?,?);";
|
|
try (Connection con = DataSourceProvider.getDataSource().getConnection();
|
|
PreparedStatement ps = con.prepareStatement(sql)) {
|
|
ps.setInt(1, orderId);
|
|
ps.setString(2, item.getItemName());
|
|
ps.setInt(3, item.getQuantity());
|
|
ps.setInt(4, item.getPrice());
|
|
ps.execute();
|
|
} catch (SQLException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
public static void saveOrderItems(List<OrderItem> items, int orderId) {
|
|
for (OrderItem item: items){
|
|
saveOrderItem(item, orderId);
|
|
}
|
|
}
|
|
|
|
public static void deleteOrderItemsForOrderId(int id) {
|
|
String sql = "delete from order_items where ORDER_ID=?";
|
|
try (Connection con = DataSourceProvider.getDataSource().getConnection();
|
|
PreparedStatement ps = con.prepareStatement(sql)) {
|
|
ps.setInt(1, id);
|
|
ps.executeUpdate();
|
|
} catch (SQLException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
}
|