我的Grails应用程序中有以下服务:
class Person {
String name
}
class Host {
String url
}
然后我有一个由多个并发线程调用的方法:
def person = Person.findByName("Coco")
def host = Host.findByUrl("some_url")
我是否需要使用*.withTransaction { }
块围绕这两个查询? E.g:
Person.withTransaction { def person = Person.findByName("Coco") }
Host.withTransaction { def host = Host.findByUrl("some url") }
我已阅读findBy* documentation但无法找到有关数据库事务安全的任何信息。
谢谢。
答案 0 :(得分:3)
我是否需要使用* .withTransaction {}阻止这两个查询?
您是否希望在withTransaction块中发生这种情况取决于您的应用中可能有多种因素,但要回答问题,不是。这些查询可以在您的应用中的任何位置执行。
答案 1 :(得分:1)
正如杰夫已经说过的那样,每个查询都需要做成事务性的,但整个上下文可能都是。
问题是,如果你不在TX-context中做
def person = Person.findByName("Coco")
然后下面几行:
def children = person.lazyLoadedChildren
然后你会得到LazyInitException
答案 2 :(得分:0)
如果您正在创建自己的线程,那么他们需要限制会话。否则你将无法使用所有的hibernate方法。 我发现的最好方法是使用persistenceInterceptor:
import org.codehaus.groovy.grails.support.PersistenceContextInterceptor
PersistenceContextInterceptor persistenceInterceptor //get this from the context
void someMethod(){
persistenceInterceptor.init()
try {
//Here you can use dynamic finders and everything
} finally {
persistenceInterceptor.flush()
persistenceInterceptor.destroy()
}
}