【问题标题】:Spring user transaction with hibernate使用休眠的 Spring 用户事务
【发布时间】:2009-07-22 07:37:11
【问题描述】:

我想自己控制休眠事务,以便随时回滚。我调用一个线程来做生意,但不等待它完成工作并更新数据库。此更新仅在方法结束时可用,但我想在每个 for 循环中提交更改,因此我需要控制休眠事务。

我的示例代码如下:

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");
            }
        }

有什么建议吗?

【问题讨论】:

  • 那段代码不是很有趣,我们需要看看做休眠工作的那段代码。

标签: java hibernate spring transactions


【解决方案1】:

查看 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();
        }
    });
}

【讨论】:

  • 谢谢。交易模板适合我。
猜你喜欢
  • 1970-01-01
  • 2015-10-15
  • 2011-08-19
  • 2011-11-16
  • 1970-01-01
  • 2012-11-11
  • 2016-03-19
  • 2011-06-23
  • 1970-01-01
相关资源
最近更新 更多