我有这些实体: 汽车/车辆/汽车/ CustomDTO
Car
- long carId
Vehicle
- long vehicleId;
Auto
- long autoTypeId;
CustomDTO
- long autoTypeId;
- String autoTypeName;
- List<Car> cars;
public List<Car> getCarByVehicleAndType(long vehicleId, long autoTypeId){
List<Car> cars = new ArrayList<Car>();
List<Car> carsInCarVehicleType = carService.getCarsInCarVehicleType(vehicleId, autoTypeId); //DAO Fetch cars IN Cat-Vehicle-Type table
for(Car car : carsInCarVehicleType){
car.selected(true);
}
List<Car> carsNotInCarVehicleType = carService.getCarsNotInCarVehicleType(vehicleId, autoTypeId); //DAO Fetch cars NOT IN Cat-Vehicle-Type table
for(Car car : carsNotInCarVehicleType){
car.selected(false);
}
cars.addAll(carsInCarVehicleType);
cars.addAll(carsNotInCarVehicleType);
return cars;
}
public List<CustomDTO> constructVehicleDTO(long vehicleId){
List<Auto> autos = autoService.getAutos(); //DAO Fetch all autos
List<CustomDTO> dtoList = new ArrayList<CustomDTO>();
for(Auto auto : autos){
CustomDTO dto = new CustomDTO();
dto.setAutoTypeId(auto.getAutoTypeId());
dto.setAutoTypeName(auto.getAutoTypeName());
dto.setCars(getCarByVehicleAndType(vehicleId, auto.getAutoTypeId());
dtoList.add(dto);
}
return dtoList;
}
在上面的方法中 - 当返回dtoList时, dto.setCars(...)
会被最后一次迭代值覆盖。因此,对于每辆车,我都会获得相同的车辆清单。这不会发生在普通的Java操作中。我怀疑我在这里混淆了Hibernate对象的生命周期。
如果我不清楚,请告诉我。