我想自己控制hibernate事务,这样我就可以随时回滚。我调用一个线程来做生意,但不等待它完成其工作并更新数据库。此更新仅在方法结束时可用,但我想在每个 for 循环中提交更改,因此我需要控制 hibernate 事务。
我的示例代码如下:
for(BaseFileprocess fileProcess : unprocessedFiles) {
BaseFileprocessfunctype functionType = fileProcessFunctionTypeService.findBySerno(fileProcess.getFunctioncodeserno());
if(functionType != null) {
taskExecutor.execute(new ServiceCallThread(functionType.getFunctionname(), fileProcess.getSerno(), fileProcess.getFilename()));
fileProcess.setStatu("1");
fileProcessService.update(fileProcess);//I need commit here
}
else {
System.out.println("There is no defined Function Type");
}
}
有什么建议吗?
最佳答案
查看 Spring 的 transactionTemplate 。来自文档:
// single TransactionTemplate shared amongst all methods in this instance
private final TransactionTemplate transactionTemplate;
// use constructor-injection to supply the PlatformTransactionManager
public SimpleService(PlatformTransactionManager transactionManager) {
Assert.notNull(transactionManager, "The 'transactionManager' argument must not be null.");
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
public Object someServiceMethod() {
return transactionTemplate.execute(new TransactionCallback() {
// the code in this method executes in a transactional context
public Object doInTransaction(TransactionStatus status) {
updateOperation1();
return resultOfUpdateOperation2();
}
});
}
关于java - Spring 用户事务与 hibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1163656/