Hibernate 我可以在内部提交事务关闭吗
我可以在Hibernate 我可以在内部提交事务关闭吗,hibernate,grails,gorm,Hibernate,Grails,Gorm,我可以在with transaction闭包中提交吗?我想在我的Quartz工作中做类似的事情: Author.withTransaction { def author = Author.get(1) author.staus = 'processing' author.save() commit // how can i do this? // so some work here which takes 1-2 minutes author.st
with transaction
闭包中提交吗?我想在我的Quartz
工作中做类似的事情:
Author.withTransaction {
def author = Author.get(1)
author.staus = 'processing'
author.save()
commit // how can i do this?
// so some work here which takes 1-2 minutes
author.status = 'completed'
author.save()
}
我的想法是,我希望有一个状态屏幕,显示当前正在处理的所有作者
,因此我希望将状态设置为处理
,并能够从控制器上查看此状态
编辑:
如果没有
with transaction
,这将起作用,但我必须在那里使用with transaction
。。。请参阅。为了从不同的未提交事务中读取值,必须将数据库隔离级别设置为“read uncommitted”(读取未提交),这通常表示您可能做错了什么
是否有任何原因使您无法将此拆分为单独的事务?一个将记录标记为“进行中”,另一个将执行实际工作
Author.withTransaction {
def author = Author.get(id)
author.status = 'processing'
author.save()
}
Author.withTransaction() {
def author = Author.get(id)
// do some work
author.status = 'completed'
author.save()
}
我会尽可能地坚持@codelark的方法,以编程方式处理事务并添加回滚逻辑 这是一个共同的事件,我也在这个问题上与科德拉克挖掘理由。以下是我现在拥有的:
Author.withSession{session->
def author = Author.get(blahId)
try{
def tx = session.beginTransaction()
//Update status to processing
author.status = 'processing'
tx.commit()
//Do your 1 - 3 minutes task
} catch(e){
//If there is any exception in that task then rollback transaction
tx?.setRollbackOnly()
}
if(!tx.isRollbackOnly()){
try {
def tx2 = session.beginTransaction()
//Update author status to completed
//Few pain points can also be taken care of here, like checking if the task completed as expected etc..
author.status = 'completed'
tx2.commit()
}
catch(Exception e) {
tx2?.setRollbackOnly() //If you want
}
}
}
@Alidad说commit/flush发生在
withTransaction
块的末尾是绝对正确的。所以flush:true
insidewithTransaction
将不起作用。提交将在每个事务结束时发生。我知道这一点。我想问的是,是否有一种方法可以在内使用事务执行提交?作业将按照作者执行或批量执行?除了延迟加载问题之外,您是否需要将其作为事务性的?不,我将其设置为事务性的,只是为了避开延迟加载问题。很好。我这里只有一个问题,如果第二个事务中的任务发生了不好的情况,如何回滚第一个事务?有几种方法。我会将其包装在服务方法中并使用嵌套事务。但是,如果您想坚持程序化的tx管理,您可以自己在第二个事务中捕获异常,使用TransactionStatus
参数导致回滚,并具有逻辑在事件发生后回滚第一个事务。快速编辑-“回滚第一个”不是一个正确的术语,因为您实际上只是执行另一个更新来清除状态。您是正确的。我同意。那是我的解决方案。。。我只是想知道是否有办法用一个withTransaction
。谢谢你的回答。