我正在编写一个汽车租赁应用程序,我的数据库中有两个表,Cars
并且Bookings
. 以下是每个字段:
Cars
CarID | Make | Model | Year
Bookings
BookingID | CarID | UserID | StartDate | EndDate | Paid
我正在编写一个称为getCars()
返回ArrayList
类型的方法Car
。在我的Car
班上,我有另一个ArrayList
叫bookings
,它保存了那辆车的所有预订。我可以在 的构造函数中插入预订Car
,如下所示:
public Car(Integer carId, String make, String model, Integer year, ArrayList<Booking> bookings) {
this.carId = carId;
this.make = make;
this.model = model;
this.year = year;
this.bookings = bookings;
}
但是,我无法从我的数据库中获取汽车和预订信息,然后Car
从结果中构造正确的对象。我正在尝试这个:
String query = "SELECT * FROM Cars INNER JOIN Bookings ON Bookings.CarID = Cars.CarID";
PreparedStatement pstmt = conn.prepareStatement(query);
results = pstmt.executeQuery();
ArrayList<Booking> bookings = new ArrayList<Booking>();
while(results.next()) {
bookings.add(new Booking(
results.getDate("StartDate"),
results.getDate("EndDate"),
results.getBoolean("Paid"),
results.getString("HouseName"),
results.getString("AddrFirstLine"),
results.getString("AddrSecondLine"),
results.getString("PostCode")
));
cars.add(new Car(
results.getInt("CarID"),
results.getString("Make"),
results.getString("Model"),
results.getInt("Year"),
bookings
));
}
它有点工作,但会产生重复的结果。如果一辆车有两个预订,它将Car
为同一辆车创建两个实例,而不是一个具有多个Car.bookings
. 它还将提供Car
数据库中的每个预订,如下所示:
在这种情况下如何正确构造Car
对象?
谢谢!