2012-10-17 145 views
1

當服務發生配置爲回滾(rollbackfor)的異常時,此回滾無效。Hibernate + Spring事務回滾不起作用

服務類:

@Service("bookService") 
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { BusinessException.class }, readOnly = true) 
public class BookServiceImpl implements BookService { 

    @Autowired 
    private BookRepository bookDAO; 

    @Override 
    @Transactional(readOnly = false) 
    public void transactionTest(Book book) throws BusinessException { 
      try { 
       bookDAO.test(book); 
      } catch (DAOException e) { 
       throw new BusinessException("test rollback - service"); 
      } 
    } 
} 

庫類:

@Repository("bookRepository") 
public class BookRepositoryImpl implements BookRepository { 

    @Autowired 
    private SessionFactory sessionFactory; 

@Transactional(readOnly = false) 
@Override 
public Book saveOrUpdate(Book book) { 
    if (book.getId() != null) { 
     getSession().merge(book); 
    } else { 
     getSession().save(book); 
    } 
    return book; 
} 

@Transactional(readOnly = false) 
@Override 
public void test(Book book) throws DAOException { 

    saveOrUpdate(book); 
    System.out.println(book.getTitle() + " inserted!"); 
    throw new DAOException("Test rollback"); 
} 

} 

有跡象表明,回滾作品之一局面。爲此,我需要更改BookServiceImpl,刪除readOnly = true,並刪除「transactionTest」方法的「@Transactional(readOnly = false)」。但是,出於安全原因,我想用readOnly的=適用於所有類,並指定什麼方法使用readOnly的=假

目前

回答

3

對整個BookServiceImpl交易配置@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { BusinessException.class }, readOnly = true)

transactionTest重寫註釋@Transactional(readOnly = false),當你重寫註解用類來更新方法整個註釋而不是指定的屬性。

,而不是這個你應該有下面的代碼BookServiceImpl

@Service("bookService") 
@Transactional(readOnly = true) 
public class BookServiceImpl implements BookService { 

    @Autowired 
    private BookRepository bookDAO; 

    @Override 
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = { BusinessException.class },readOnly = false) 
    public void transactionTest(Book book) throws BusinessException { 
      try { 
       bookDAO.test(book); 
      } catch (DAOException e) { 
       throw new BusinessException("test rollback - service"); 
      } 
    } 
} 

,如果進一步想要同類交易對DAO(庫)的水平,那麼其指定或只是讓服務照顧有關事務(假定存儲庫不會直接與客戶端接口)。