ルーク・デイリーは正しい答えを出しました。残念ながら、リンクが変更されました。したがって、私は彼の答えを更新し、この答えを自己完結型にするためのコード例を提供します。
GrailsアプリケーションにはpersistenceInterceptor
、Hibernateの永続コンテキスト/セッションを初期化するために使用できるBeanがあります。次のコードスニペットを使用して、Beanをコントローラー/サービスクラスの1つに挿入し、新しいスレッドを開始できます。
class YourControllerOrService {
PersistenceContextInterceptor persistenceInterceptor
def someOperation() {
...
Runnable yourTask = { ->
try {
if (persistenceInterceptor) {
persistenceInterceptor.init()
}
// execute the hibernate operations here in a transaction,
// e.g. call a method annotated with @Transactional
...
} catch (Exception e) {
log.error('Your error message', e)
} finally {
if (persistenceInterceptor) {
persistenceInterceptor.flush()
persistenceInterceptor.destroy()
}
}
}
Thread workerThread = new Thread(yourTask)
workerThread.start()
...
}
}
GitHubのGrailsJMSプラグインに例示的な実装があります。
PersistenceContextInterceptorインターフェイスはGitHubにもあります。