当服务抛出配置为回滚(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