외래 키 관계를 롤백해야하지만 트랜잭션을 버리기를 원하지 않는다면 (즉, 다른 데이터를 계속 저장하는) Hibernate 모범 사례는 무엇입니까?Hibernate와의 외래 키 관계 롤백
예외를 전달하거나이 롤백을 수행하지 않으면 BookingLines가 유지되는 동안 다른 데이터 (Null 또는 일시적 객체 전달 지속됨)를 저장하려고 할 때 오류가 발생합니다. 이미 지속되었다.
나는 현재 다음과 같이 실패 엔티티 목록에서 제거 후지도에 새로운 요소를 추가하고하여 롤백을 처리 :이 작동하지만 나쁜 느낌
/* 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));
}
}
. 더 좋은 방법이 있습니까?
bookingLine.clear()
은 이미 저장된 다른 InvoiceLines에 연결되어있을 수 있으므로 좋지 않습니다.
감사합니다.
당신이하는 일은 '보상 거래'라고합니다. 귀하의 경우 귀하는 현재 거래가 진행되는 동안 그 거래를 취소하고 싶습니다. 기본적으로 커밋/롤백과 같은 역할은 사용할 수 없지만 단일 트랜잭션 경계 내에 머물러 있어야합니다. 나는 당신이 참으로 같은 것을 성취하기 위해 커밋/롤백을 사용할 수 없다는 것을 감안할 때 아무런 문제가 없을 것이다. – topchef