我有一個Spring @Service
bean,其中一些數據保存在MySQL發生。這是節省LocalDateTime
對象,在未來的日期預訂房間。Spring @Transactional在失敗後不回滾
問題是:當一次預訂多個房間並且其中一個房間不可用(即已經預訂)時,Spring應該回滾已經預訂但尚未預訂的所有房間。除錯誤之外的所有內容都被提交給數據庫。
我的@Service
中的代碼,應該在拋出異常後回滾的代碼。
@Transactional(rollbackFor = { RecurrentMeetingBookingException.class})
public void bookRecurringMeeting(RecurrentMeeting meeting) throws RecurrentMeetingBookingException {
LocalDateTime start = meeting.getMeetingEntity().getStartDate();
LocalDateTime end = meeting.getMeetingEntity().getEndDate();
while (start.isBefore(meeting.getRecurrenceEndTime())) {
MeetingEntity recurrent = copyOfRecurrent(meeting, start, end);
try {
bookRoomForDate(recurrent);
} catch (MeetingException e) {
throw new RecurrentMeetingBookingException(e.getMessage());
}
start = start.plus(1, meeting.getRecurrenceType().getUnitOfTime());
end = end.plus(1, meeting.getRecurrenceType().getUnitOfTime());
}
}
我也試過投擲RuntimeException
,但它也沒有工作。
從我的Controller
返回ResponseEntity
時,確實會拋出異常,因爲我將Room is not available
作爲例外返回,並返回它的消息。
我的@Transactional
有什麼問題?不應該在拋出異常時Spring/Hibernate回滾所有內容嗎?我能做些什麼來解決這個問題,並正確回滾@Transactional
?
假設'bookRecurringMeeting'方法在名爲'BookService'的'@ Service'類中聲明,'@ Controller'使用瞭如何依賴BookService類。如果你的'@ RequestMapping'不是直接調用'bookRecurringMeeting'方法,那麼'@Transactional'屬性就不能工作。考慮發佈你的'@ Controller'代碼。我也有這種行爲。 –
我的問題是另一個,我發佈在下面。花費太多時間找到解決方案,不要將其發回社區。當我有機會時,我會添加額外的代碼,但是@ RestController直接調用'bookRecurringMeeting'。 – MoisesCol
您是否已經聲明瞭或@ @TransactionTransactionManagement?請參閱https://stackoverflow.com/questions/26203446/spring-hibernate-could-not-obtain-transaction-synchronized-session-for-current/26203682#26203682 –