我有以下代码:
public int makePayment(User forUser, Collection<Movie> cartItems,
Address deliverTo)
{
int returnCode = 0;
LOGGER.debug("Number of items in cart - {}", cartItems.size());
Rental rental = new Rental();
rental.setRentalID(RandomStringUtils.randomAlphanumeric(ID_LENGTH).toUpperCase());
rental.setUser(forUser); // Update reference to parent
rental.setAddress(deliverTo);
// Each rental has its own set of rented movies
Set<RentedMovie> rentedMovies = new HashSet<>(cartItems.size());
for (Iterator<Movie> iterator = cartItems.iterator(); iterator.hasNext();)
{
Movie movie = iterator.next();
RentedMovie rentedMovie = new RentedMovie();
rentedMovie.setMovie(movie);
rentedMovie.setRental(rental); // Update reference to parent
rentedMovies.add(rentedMovie);
}
rental.setRentedMovies(rentedMovies);
rentalDAO.create(rental);
Set<Rental> userRentals = userDAO.findById(forUser.getUserID()).getRentals();
userRentals.add(rental); // Add to existing set of rentals
try
{
String addressID = addressDAO.create(deliverTo);
LOGGER.debug("Delivery Address successfully inserted. Generated address ID - {}", addressID);
forUser.setRentals(userRentals);
userDAO.update(forUser); // Internally calls session.merge()
}
catch (Exception e) {
returnCode = -1;
LOGGER.error("Exception during payment - {}", e.getMessage(), e);
}
return returnCode;
}
现在,当上述方法完成时,hibernate 会执行某些冗余更新查询,如下所述:
假设我在购物车中添加了 2 件商品,所以...
DEBUG PaymentService - Number of items in cart - 2
接下来,在表中插入一行RENTALS
(预期)
insert
into
rentals
(bookingDate, userID, addressID, rentalID)
values
(?, ?, ?, ?)
USER
和ADDRESS
表更新一次,因为插入了 1 行RENTALS
(冗余)
update
users
set
userName=?,
password=?,
firstName=?,
lastName=?,
email=?,
addressID=?
where
userID=?
update
addresses
set
line1=?,
line2=?,
city=?,
state=?,
pincode=?
where
addressID=?
MOVIES
表的更新次数与购物车中的商品数量一样多(在这种情况下为 2,再次是多余的)
update
movies
set
movieName=?,
releaseYear=?,
rating=?,
nCopies=?,
imageUri=?,
plotLine=?
where
movieID=?
/* And another query with different movieID */
表中插入 2 条记录RENTED_MOVIE
(预期)
insert
into
rented_movie
(rentalID, returnDate, movieID)
values
(?, ?, ?)
/* And one more with same rentalID and diff. movieID */
最后但并非最不重要的一点是对表的选择查询RENTALS
(为什么??)
上述冗余查询的原因是什么?
我正在使用 Hibernate 4.2.1 和 MySQL 5.5
链接到架构图
链接到User.hbm.xml
更新:似乎无论inverse
我尝试什么可能的组合,我似乎都无法避免这些 n+2 更新(n = 购物车中的电影数):(
有人可以让我知道这是否是已知行为吗?如果是,可能的解决方法是什么?