forked from AdvancedProgramming1404/WS-10-Database
database
This commit is contained in:
@@ -1,25 +1,130 @@
|
||||
package dev.dao;
|
||||
|
||||
import dev.database.DatabaseConnection;
|
||||
import dev.model.Order;
|
||||
|
||||
import java.sql.*;
|
||||
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,total_price) VALUES(?,?)";
|
||||
|
||||
|
||||
try(Connection con = DatabaseConnection.getConnection();
|
||||
|
||||
PreparedStatement ps =
|
||||
con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)){
|
||||
|
||||
|
||||
ps.setInt(1, order.getUserId());
|
||||
|
||||
ps.setDouble(2, order.getTotalPrice());
|
||||
|
||||
|
||||
ps.executeUpdate();
|
||||
|
||||
|
||||
|
||||
ResultSet rs = ps.getGeneratedKeys();
|
||||
|
||||
|
||||
if(rs.next()){
|
||||
|
||||
return rs.getInt(1);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}catch(SQLException e){
|
||||
|
||||
e.printStackTrace();
|
||||
|
||||
}
|
||||
|
||||
|
||||
return -1;
|
||||
|
||||
}
|
||||
|
||||
public List<Order> findByUserId(int userId) {
|
||||
|
||||
// TODO:
|
||||
// Retrieve all orders of a user
|
||||
|
||||
return null;
|
||||
|
||||
public List<Order> findByUserId(int userId){
|
||||
|
||||
|
||||
List<Order> orders = new ArrayList<>();
|
||||
|
||||
|
||||
String sql =
|
||||
"SELECT * FROM orders WHERE user_id=?";
|
||||
|
||||
|
||||
try(Connection con = DatabaseConnection.getConnection();
|
||||
|
||||
PreparedStatement ps =
|
||||
con.prepareStatement(sql)){
|
||||
|
||||
|
||||
ps.setInt(1,userId);
|
||||
|
||||
|
||||
|
||||
ResultSet rs = ps.executeQuery();
|
||||
|
||||
|
||||
|
||||
while(rs.next()){
|
||||
|
||||
|
||||
Order order = new Order();
|
||||
|
||||
|
||||
order.setId(rs.getInt("id"));
|
||||
|
||||
order.setUserId(rs.getInt("user_id"));
|
||||
|
||||
order.setTotalPrice(
|
||||
rs.getDouble("total_price")
|
||||
);
|
||||
|
||||
|
||||
Timestamp timestamp =
|
||||
rs.getTimestamp("created_at");
|
||||
|
||||
|
||||
if(timestamp != null){
|
||||
|
||||
order.setCreatedAt(
|
||||
timestamp.toLocalDateTime()
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
|
||||
orders.add(order);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}catch(SQLException e){
|
||||
|
||||
e.printStackTrace();
|
||||
|
||||
}
|
||||
|
||||
|
||||
return orders;
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user