-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProductDAO.java
More file actions
77 lines (63 loc) · 2.54 KB
/
Copy pathProductDAO.java
File metadata and controls
77 lines (63 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ProductDAO {
public ProductDTO getProduct(String productId) {
String sql = "SELECT product_id, name, price, category FROM products WHERE product_id = ?";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, productId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return new ProductDTO(
rs.getString("product_id"),
rs.getString("name"),
rs.getBigDecimal("price"),
rs.getString("category")
);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public List<ProductDTO> getAvailableProducts(String machineId) {
String sql = "SELECT p.product_id, p.name, p.price, p.category, i.quantity " +
"FROM products p " +
"JOIN inventory i ON p.product_id = i.product_id " +
"WHERE i.machine_id = ? AND i.quantity > 0";
List<ProductDTO> products = new ArrayList<>();
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, machineId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
products.add(new ProductDTO(
rs.getString("product_id"),
rs.getString("name"),
rs.getBigDecimal("price"),
rs.getString("category")
));
}
} catch (SQLException e) {
e.printStackTrace();
}
return products;
}
public boolean decrementInventory(String machineId, String productId) {
String sql = "UPDATE inventory SET quantity = quantity - 1 " +
"WHERE machine_id = ? AND product_id = ? AND quantity > 0";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, machineId);
stmt.setString(2, productId);
return stmt.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}