什麼是Hibernate的最佳實踐,當回滾外鍵關係,但不想拋出事務(即仍然繼續保存其他數據)?回滾與休眠的外鍵關係
如果我只是通過異常備份堆棧或不執行此回滾,那麼當我試圖保存其他數據(傳遞給持久化的空值或瞬態對象)時,我會遇到一個錯誤,因爲BookingLines是已經堅持。
我目前通過添加新的實體到地圖,然後從實體列表上的失敗刪除它們如下處理回滾:
/* Method that will try to create an invoice but won't roll back the transaction if
* a currency rate can't be found.
*/
public void createInvoiceFromBooking(Booking booking) {
Invoice invoice = new Invoice();
//Map to hold entities that I want to roll back
Map<BookingLine, InvoiceLine> addedLines = new HashMap<BookingLine, InvoiceLine>();
try {
for(BookingLine bookingLine : booking.getBookingLines()) {
InvoiceLIne invoiceLIne = new InvoiceLIne();
//do stuff that can throw exception
applyCurrencyRate(invoiceLine);
bookingLine.getInvoiceLines().add(invoiceLine);
invoice.getInvoiceLines().add(invoiceLine);
//add to the "rollback" map
addedLines.put(bookingLine, invoiceLine);
}
} catch (Exception e) {
//remove the InvoiceLines from the related entities
for(BookingLine bookingLine : addedLines.keySet()) {
bookingLine.getInvoiceLines().remove(addedLines.get(bookingLine));
}
}
這工作,但感覺罪惡。有沒有更好的辦法?
A bookingLine.clear()
不好,因爲它可能有其他已保存的與其關聯的InvoiceLines。
謝謝。
你所做的就是所謂的'補償交易'。在你的情況下,你想保留當前的交易,同時撤消它的一部分。基本上,你的行爲像提交/回滾不可用於你,但你留在一個單一的事務邊界。我沒有問題,因爲你確實無法使用commit/rollback來完成相同的操作。 – topchef 2009-06-16 04:15:52