我有以下情况(当然是简化的):
MyDomain.groovy:
class MyDomain {
MyAnotherDomain anotherDomain // lazy loaded
}
MyService.groovy:
class MyService {
boolean transactional = true
def doSomething(id) {
// ... some code...
}
}
MYController.groovy:
class MyController {
def myService
def doAction = {
MyDomain aaa = ...GET_IT_FROM_SOMEWHERE...
try {
myService.doSomething(id)
} catch (RuntimeError e) {
flash.message = 'sorry.guy.your.transaction.was.rollbacked'
}
[myData: aaa]
}
}
doAction.gsp:
<html>
<body>
${myData.anotherDomain}
</body>
</html>
当doSomething()抛出RuntimeException时,就会发生问题。此RuntimeException回滚事务也将结束Hibernate session 。当我在RuntimeError之后呈现doAction.gsp时,它以错误结尾,因为无法读取延迟加载的字段anotherDomain(无 session )。现在您可以说“确定,不要使用RuntimeException”,但是我需要自动事务回滚。
有什么想法即使在事务服务中发生RuntimeException时也如何保持Hibernate session 打开,以便可以正确呈现gsp中的延迟加载?谢谢。
最佳答案
如果您的Hibernate session 在回滚和Xception throw 期间被破坏,则可以尝试将其手动重新附加到当前的Hibernate session 中:
MyController.groovy:
class MyController {
def myService
def doAction = {
MyDomain aaa = ...GET_IT_FROM_SOMEWHERE...
try {
myService.doSomething(id)
} catch (RuntimeError e) {
flash.message = 'sorry.guy.your.transaction.was.rollbacked'
if(!aaa.isAttached()) {
aaa.attach()
}
}
[myData: aaa]
}
}
希望适合您的需求。
Reference
关于exception - 使用View-Controller-Service体系结构在Grails中运行时错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2252427/