Implement database, daos and other classes

This commit is contained in:
2026-07-03 23:33:16 +03:30
parent 00f990c653
commit c2bf0b8222
23 changed files with 732 additions and 164 deletions
+54 -6
View File
@@ -1,25 +1,73 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.MenuItem;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MenuItemDao {
public List<MenuItem> findAll() {
// TODO:
// Retrieve all menu items
String sql = "SELECT * FROM menu";
List<MenuItem> result = new ArrayList<>();
return null;
try{
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
ResultSet rs = st.executeQuery();
while(rs.next()){
result.add(new MenuItem(
rs.getInt("id"),
rs.getString("name"),
rs.getString("description"),
rs.getDouble("price"),
rs.getString("category")
));
}
st.close();
} catch (SQLException e) {
System.err.println("Failed to fetch menu " + e.getMessage());
}
return result;
}
public MenuItem findById(int id) {
// TODO:
// Find menu item by id
String sql = "SELECT * FROM menu WHERE id=?";
MenuItem itemMenu = null;
try{
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setInt(1, id);
ResultSet rs = st.executeQuery();
if(rs.next()){
itemMenu = new MenuItem(
rs.getInt("id"),
rs.getString("name"),
rs.getString("description"),
rs.getDouble("price"),
rs.getString("category")
);
}
st.close();
} catch (SQLException e) {
System.err.println("Failed to fetch item " + e.getMessage());
}
return itemMenu;
return null;
}
}
+53 -5
View File
@@ -1,25 +1,73 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.Order;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
public class OrderDao {
public int save(Order order) {
// TODO:
// Insert order and return generated id
String sql = "INSERT INTO orders(user_id, created_at, total_price) VALUES(?, ?, ?)";
try{
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setInt(1, order.getUserId());
st.setTimestamp(2, Timestamp.valueOf(order.getCreatedAt()));
st.setDouble(3, order.getTotalPrice());
st.executeUpdate();
ResultSet rsKeys = st.getGeneratedKeys();
if(rsKeys.next()){
int orderId = rsKeys.getInt(1);
order.setId(orderId);
return orderId;
}
st.close();
} catch (SQLException e) {
System.err.println("Failed to add order " + e.getMessage());
}
return -1;
}
public List<Order> findByUserId(int userId) {
// TODO:
// Retrieve all orders of a user
String sql = "SELECT * FROM orders WHERE user_id=?";
List<Order> result = new ArrayList<>();
try {
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setInt(1,userId);
ResultSet rs = st.executeQuery();
while (rs.next()){
result.add(new Order(
rs.getInt("id"),
rs.getInt("user_id"),
rs.getTimestamp("created_at").toLocalDateTime(),
rs.getInt("total_price")
));
}
st.close();
} catch (SQLException e) {
System.err.println("Unable to find user: " + e.getMessage());
}
return result;
return null;
}
}
+47 -5
View File
@@ -1,24 +1,66 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.OrderDetail;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class OrderDetailDao {
public void save(OrderDetail detail) {
// TODO:
// Insert order detail
String sql = "INSERT INTO order_details (order_id, menu_id, quantity, item_price) VALUES (?,?,?,?)";
try {
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setInt(1, detail.getOrderId());
st.setInt(2, detail.getMenuItemId());
st.setInt(3, detail.getQuantity());
st.setDouble(4, detail.getPrice());
st.executeUpdate();
st.close();
} catch (SQLException e) {
System.err.println("Error writing order details: " + e.getMessage());
}
}
public List<OrderDetail> findByOrderId(int orderId) {
// TODO:
// Retrieve order details
List<OrderDetail> result = new ArrayList<>();
return null;
String sql = "SELECT * FROM order_details WHERE order_id=?";
try {
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setInt(1,orderId);
ResultSet rs = st.executeQuery();
while (rs.next()){
result.add(new OrderDetail(
rs.getInt("id"),
rs.getInt("order_id"),
rs.getInt("menu_id"),
rs.getInt("quantity"),
rs.getDouble("item_price")
)
);
}
st.close();
} catch (SQLException e) {
System.err.println("Error retrieving order details: " + e.getMessage());
}
return result;
}
}
+45 -5
View File
@@ -1,23 +1,63 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
public boolean save(User user) {
// TODO:
// Insert user into database
String sql = "INSERT INTO users (username, password_hash, email) VALUES (?, ?, ?)";
try{
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setString(1, user.getUsername());
st.setString(2, user.getPassword());
st.setString(3, user.getEmail());
st.executeUpdate();
st.close();
return true;
} catch (SQLException e) {
System.err.println("Failed to save user " + e.getMessage());
}
return false;
}
public User findByUsername(String username) {
// TODO:
// Find a user by username
String sql = "SELECT * FROM users WHERE username=?";
User result = null;
try{
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setString(1, username);
ResultSet rs = st.executeQuery();
if(rs.next()){
result = new User(
rs.getInt("id"),
rs.getString("username"),
rs.getString("password_hash"),
rs.getString("email")
);
}
st.close();
} catch (SQLException e) {
System.err.println("Failed to fild user " + e.getMessage());
}
return result;
return null;
}
}
@@ -1,15 +1,16 @@
package dev.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:postgresql://localhost:5432/restaurant_db"; // DB Server
private static final String USER = "postgres"; // Your Username
private static final String USER = "matin"; // Your Username
private static final String PASSWORD = "password"; // Your Password
private static final String PASSWORD = "0000"; // Your Password
private DatabaseConnection() {
@@ -18,10 +19,8 @@ public class DatabaseConnection {
public static Connection getConnection()
throws SQLException {
// TODO:
// Return a valid PostgreSQL connection
return DriverManager.getConnection(URL, USER, PASSWORD);
return null;
}
}
+38 -4
View File
@@ -3,13 +3,47 @@ package dev.model;
public class MenuItem {
private int id;
private String name;
private String description;
private double price;
private String category;
public MenuItem(int id, String name, String description, double price, String category) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
this.category = category;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public double getPrice() {
return price;
}
public String getCategory() {
return category;
}
@Override
public String toString() {
return "MenuItem{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", price=" + price +
", category='" + category + '\'' +
'}';
}
}
+54 -3
View File
@@ -5,11 +5,62 @@ import java.time.LocalDateTime;
public class Order {
private int id;
private int userId;
private LocalDateTime createdAt;
private int totalPrice;
private double totalPrice;
public Order(int id, int totalPrice, LocalDateTime createdAt, int userId) {
this.id = id;
this.totalPrice = totalPrice;
this.createdAt = createdAt;
this.userId = userId;
}
public Order(int userId, LocalDateTime createdAt, int totalPrice) {
this.userId = userId;
this.createdAt = createdAt;
this.totalPrice = totalPrice;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(int totalPrice) {
this.totalPrice = totalPrice;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", userId=" + userId +
", createdAt=" + createdAt +
", totalPrice=" + totalPrice +
'}';
}
}
+65 -4
View File
@@ -3,13 +3,74 @@ package dev.model;
public class OrderDetail {
private int id;
private int orderId;
private int menuItemId;
private int quantity;
private double price;
public OrderDetail(int id, int orderId, int menuItemId, int quantity, double price) {
this.id = id;
this.orderId = orderId;
this.menuItemId = menuItemId;
this.quantity = quantity;
this.price = price;
}
public OrderDetail(int orderId, int menuItemId, int quantity, double price) {
this.orderId = orderId;
this.menuItemId = menuItemId;
this.quantity = quantity;
this.price = price;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getMenuItemId() {
return menuItemId;
}
public void setMenuItemId(int menuItemId) {
this.menuItemId = menuItemId;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "OrderDetail{" +
"id=" + id +
", orderId=" + orderId +
", menuItemId=" + menuItemId +
", quantity=" + quantity +
", price=" + price +
'}';
}
}
+34 -3
View File
@@ -3,11 +3,42 @@ package dev.model;
public class User {
private int id;
private String username;
private String password;
private String email;
// verify user for the first time
public User(int id, String username, String password, String email){
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
// verified user
public User(String username, String password, String email){
this.username = username;
this.password = password;
this.email = email;
}
public void setId(int id){
this.id = id;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getEmail() {
return email;
}
}
+23 -4
View File
@@ -1,21 +1,40 @@
package dev.service;
import dev.dao.UserDao;
import dev.model.User;
import java.util.Objects;
public class AuthService {
private final UserDao userDao = new UserDao();
public boolean register(String username, String password, String email) {
// TODO:
// Validate and register user
User user = new User(
username,
String.valueOf(password.hashCode()),
email
);
if(userDao.save(user)){
System.out.println("Registered successfully");
return true;
}
return false;
}
public User login(String username, String password) {
// TODO:
// Authenticate user
User userDB = userDao.findByUsername(username);
if(userDB == null) return null;
String userPasswordDB = userDB.getPassword();
if( Objects.equals( userPasswordDB, String.valueOf(password.hashCode()) ) )
return userDB;
return null;
}
+11 -2
View File
@@ -1,11 +1,20 @@
package dev.service;
import dev.dao.MenuItemDao;
import dev.model.MenuItem;
import java.util.List;
public class MenuService {
public static final MenuItemDao menuItemDao = new MenuItemDao();
public void showMenu() {
// TODO:
// Display menu items
List<MenuItem> items = menuItemDao.findAll();
for(MenuItem item : items){
System.out.println(item);
}
}
+122 -6
View File
@@ -1,25 +1,141 @@
package dev.service;
import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.model.MenuItem;
import dev.model.Order;
import dev.model.OrderDetail;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
public class OrderService {
private final static OrderDetailDao orderDetailDao = new OrderDetailDao();
private final static OrderDao orderDao = new OrderDao();
private final static MenuService menuService = new MenuService();
private final static Scanner scanner = new Scanner(System.in);
public void placeOrder(int userId) {
// TODO:
// Create order
List<MenuItem> menuItems = MenuService.menuItemDao.findAll();
if (menuItems.isEmpty()) {
System.out.println("No menu items available.");
return;
}
// Display menu
System.out.println("========== MENU ==========");
for (MenuItem item : menuItems) {
System.out.printf("%-4d %-25s %10.2f%n",
item.getId(), item.getName(), item.getPrice());
}
System.out.println("===========================");
Order order = new Order(userId, LocalDateTime.now(), 0);
int orderId = orderDao.save(order);
double totalPrice = 0;
boolean addingItems = true;
while (addingItems) {
System.out.print("Enter menu item id to add (0 to finish): ");
int menuId = Integer.parseInt(scanner.nextLine().trim());
if (menuId == 0) {
addingItems = false;
continue;
}
MenuItem selected = MenuService.menuItemDao.findById(menuId);
if (selected == null) {
System.out.println("Invalid item id, try again.");
continue;
}
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(scanner.nextLine().trim());
if (quantity <= 0) {
System.out.println("Quantity must be positive.");
continue;
}
OrderDetail detail = new OrderDetail(
orderId,
selected.getId(),
quantity,
selected.getPrice()
);
orderDetailDao.save(detail);
totalPrice += selected.getPrice() * quantity;
System.out.println(selected.getName() + " x" + quantity + " added.");
}
if (totalPrice == 0) {
System.out.println("No items were added. Order canceled.");
return;
}
order.setId(orderId);
order.setTotalPrice((int) totalPrice);
orderDao.save(order);
System.out.println("Order placed successfully. Order ID: " + orderId);
printReceipt(orderId);
}
public void printReceipt(int orderId) {
// TODO:
// Print order receipt
List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
if(details.isEmpty())
return;
System.out.println("Order ID: " + orderId);
double total = 0;
for (OrderDetail detail : details) {
double subtotal = detail.getPrice() * detail.getQuantity();
total += subtotal;
System.out.printf("%-20s %dx $%.2f%n",
MenuService.menuItemDao.findById(detail.getMenuItemId()).getName(),
detail.getQuantity(),
subtotal
);
}
System.out.println("---------------------------");
System.out.printf("Total: $%.2f%n", total);
System.out.println("===========================\n");
}
public void showOrderHistory(int userId) {
// TODO:
// Display user's order history
List<Order> orders = orderDao.findByUserId(userId);
if (orders.isEmpty()){
System.err.println("No orders found.");
return;
}
for (Order order : orders){
System.out.println("Order ID: " + order.getId());
System.out.println("Date: " + order.getCreatedAt());
System.out.printf("Total: $%.2f%n", order.getTotalPrice());
System.out.println("---------------------------------");
printReceipt(order.getId());
}
}
+40 -7
View File
@@ -1,11 +1,15 @@
package dev.ui;
import dev.model.User;
import dev.service.AuthService;
import dev.service.MenuService;
import java.util.Scanner;
public class ConsoleMenu {
private final Scanner scanner =
new Scanner(System.in);
private final Scanner scanner = new Scanner(System.in);
private final AuthService authService = new AuthService();
public void start() {
@@ -21,13 +25,42 @@ public class ConsoleMenu {
switch (choice) {
case 1:
// TODO
break;
case 1: {
System.out.println("Enter username: ");
String username = scanner.next();
System.out.println("Enter password: ");
String password = scanner.next();
case 2:
// TODO
User user = authService.login(username, password);
if (user == null) {
System.err.println("Unable to login");
continue;
}
System.out.println("welcome! " + user.getUsername());
MenuService menuService = new MenuService();
menuService.showMenu();
break;
}
case 2: {
System.out.println("Enter username: ");
String username = scanner.nextLine();
System.out.println("Enter password: ");
String password = scanner.nextLine();
System.out.println("Enter email: ");
String email = scanner.nextLine();
if (!authService.register(username, password, email)) {
System.err.println("Registration failed.");
continue;
}
System.out.println("Registered successfully.");
break;
}
case 3:
return;