implement Order.java
This commit is contained in:
@@ -1,25 +1,67 @@
|
|||||||
package dev.dao;
|
package dev.dao;
|
||||||
|
|
||||||
|
import dev.database.DatabaseConnection;
|
||||||
import dev.model.Order;
|
import dev.model.Order;
|
||||||
|
|
||||||
|
import java.sql.*;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class OrderDao {
|
public class OrderDao {
|
||||||
|
|
||||||
public int save(Order order) {
|
public int save(Order order) {
|
||||||
|
|
||||||
// TODO:
|
|
||||||
// Insert order and return generated id
|
// Insert order and return generated id
|
||||||
|
String sql = "INSERT INTO orders (user_id, total_price, created_at) VALUES(?, ?, ?) RETURNING id";
|
||||||
|
|
||||||
|
try (Connection connection = DatabaseConnection.getConnection();
|
||||||
|
PreparedStatement preparedStatement = connection.prepareStatement(sql)){
|
||||||
|
|
||||||
|
preparedStatement.setInt(1, order.getUserId());
|
||||||
|
preparedStatement.setDouble(2, order.getTotalPrice());
|
||||||
|
preparedStatement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
|
||||||
|
|
||||||
|
ResultSet resultSet = preparedStatement.executeQuery();
|
||||||
|
|
||||||
|
if(resultSet.next()) return resultSet.getInt("id");
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Order> findByUserId(int userId) {
|
public List<Order> findByUserId(int userId) {
|
||||||
|
|
||||||
// TODO:
|
|
||||||
// Retrieve all orders of a user
|
// Retrieve all orders of a user
|
||||||
|
String sql = "SELECT * FROM orders WHERE user_id=?";
|
||||||
|
List<Order> orders = new ArrayList<>();
|
||||||
|
|
||||||
return null;
|
try(Connection connection = DatabaseConnection.getConnection();
|
||||||
|
PreparedStatement preparedStatement = connection.prepareStatement(sql) ) {
|
||||||
|
|
||||||
|
preparedStatement.setInt(1, userId);
|
||||||
|
|
||||||
|
ResultSet resultSet = preparedStatement.executeQuery();
|
||||||
|
|
||||||
|
while (resultSet.next()) {
|
||||||
|
|
||||||
|
Order order = new Order();
|
||||||
|
|
||||||
|
order.setId(resultSet.getInt("id"));
|
||||||
|
order.setUserId(resultSet.getInt("user_id"));
|
||||||
|
order.setCreatedAt(resultSet.getTimestamp("created_at").toLocalDateTime());
|
||||||
|
order.setTotalPrice(resultSet.getDouble("total_price"));
|
||||||
|
|
||||||
|
orders.add(order);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
return orders;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user