【发布时间】:2015-02-06 02:39:26
【问题描述】:
我在结合 Spring 回滚 Hibernate 更新时遇到问题。
我有以下课程:
@Service
@Transactional(readOnly = true)
public class DocumentServiceImpl extends AbstractGenericService<Document, IDocumentDao> implements DocumentService {
@Override
@Transactional(readOnly=false, rollbackFor = DocumentServiceException.class)
public void saveDocument(final DocumentForm form, final BindingResult result, final CustomUserContext userContext) throws DocumentServiceException {
Document document = locateDocument(form, userContext);
if (!result.hasErrors()) {
try {
updateDocumentCategories(form, document);
storeDocument(document, form.getDocumentId(), form.getFile());
solrService.addDocument(document);
} catch (IOException e) {
result.reject("error.uploading.file");
throw new DocumentServiceException("Error trying to copy the uploaded file to its final destination", e);
} catch (SolrServerException e) {
result.reject("error.uploading.file.solr");
throw new DocumentServiceException("Solr had an error parsing your uploaded file", e);
}
}
}
@Override
@Transactional(readOnly = false, rollbackFor = IOException.class)
public void storeDocument(Document document, String documentId, CommonsMultipartFile uploadedFile) throws IOException {
getDao().saveOrUpdate(document);
if (StringUtils.isBlank(documentId)) {
File newFile = documentLocator.createFile(document);
uploadedFile.transferTo(newFile);
// Todo: TEST FOR ROLLBACK ON FILE I/O EXCEPTION
throw new IOException("this is a test");
}
}
该接口未使用任何@Transactional 注释进行标记。 saveDocument() 方法是直接从我的 Controller 调用的,所以我希望使用该方法的 @Transactional 配置,尤其是 rollbackFor 参数。但是,当抛出 DocumentServiceException 时,不会回滚任何内容(即 getDao().saveOrUpdate(document) 被持久化)。出于测试目的,我在 storeDocument 方法中添加了一个“抛出新的 IOException”。希望有人能帮助我解决这个问题,不胜感激。
【问题讨论】:
-
@Transactional上的@Transactional注释是无用的,因为它是一个内部方法调用,只有调用代理才会应用 AOP。如果没有回滚,我怀疑您的设置有问题,实际上没有应用任何事务。另一件事是有点奇怪,恕我直言,让你的BindingResult旁边将它绑定到网络(你直接使用与网络相关的CommonsMultipartFile)。基本上你的服务层现在依赖于网络...... -
启用 spring 日志以验证事务是否开始
-
@"M. Deinum".. storeDocument 方法也被其他控制器单独调用,因此我们需要@Transactional 注解。我知道如果间接调用它是没有用的。
-
@Andy 事务有效。我通过抛出 RuntimeException(而不是 IOException)进行了另一项测试,在这种情况下,它回滚了 saveOrUpdate 提交。
标签: java spring hibernate transactions annotations