1

当服务抛出配置为回滚(rollbackfor)的异常时,此回滚不起作用。

服务等级:

@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 = true 并指定什么是方法使用 readOnly = false

4

1 回答 1

2

目前对于整个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(存储库)级别上进行相同类型的事务,则指定它或让服务来处理事务(假设存储库不会直接与客户端交互)。

于 2012-10-17T05:16:00.630 回答