2017-08-04 67 views
0

我有一個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

+0

假設'bookRecurringMeeting'方法在名爲'BookService'的'@ Service'類中聲明,'@ Controller'使用瞭如何依賴BookService類。如果你的'@ RequestMapping'不是直接調用'bookRecurringMeeting'方法,那麼'@Transactional'屬性就不能工作。考慮發佈你的'@ Controller'代碼。我也有這種行爲。 –

+0

我的問題是另一個,我發佈在下面。花費太多時間找到解決方案,不要將其發回社區。當我有機會時,我會添加額外的代碼,但是@ RestController直接調用'bookRecurringMeeting'。 – MoisesCol

+0

您是否已經聲明瞭或@ @TransactionTransactionManagement?請參閱https://stackoverflow.com/questions/26203446/spring-hibernate-could-not-obtain-transaction-synchronized-session-for-current/26203682#26203682 –

回答

0

當面臨這樣的問題,a member from the spring forums came with a solution,早在2011年


確保您使用的事務表,例如INNODB

你可能會使用非事務表,例如MyISAM@Transactional將無法​​按預期工作。

這不完全是Spring/Hibernate問題,而是數據庫的問題。