我试图在服务中创建一些线程,但我得到了 hibernateException: no session... 。我已经在 stackoverflow 中看到过关于此问题的讨论,其中包含抛出 RuntimeException 的解决方案。就我而言是行不通的。
这是我的服务代码:
class MatchService {
static transactional = true
def void start(Match match) {
Thread.start {
Match updateMatch = matchSituation(match)
if(!updateMatch.save()) {
throw new RuntimeException("match is not valid and cannot be saved!")
}
}
}
def Match matchSituation(Match m) {
Random random = new Random()
if(m.teamH.averagePlayerValue > m.teamA.averagePlayerValue) {
m.golTeamH = random.nextInt(5)
}
else {
m.golTeamA = random.nextInt(4)
}
return m
}
}
工作类别:
class TestJob {
def matchService
List<Match> matchList = new ArrayList()
static triggers = {
cron name: 'trigger', cronExpression: "0 0/1 15 ? * WED"
}
def group = "threadGroup"
def execute() {
Cal.get(1).matches.each{
match ->
matchList.add(match)
}
for(Match m: matchList) {
if(!m.validate()) {
throw new MatchException( message: "match not valid!!" , match:m)
}
matchService.start(m)
}
}
}
EDIT
使用backgroundThread插件(应该处理hibernate sessione):
backgroundService.execute("Calculating match", {
def backgroundMatch = match
backgroundMatch = matchSituation(backgroundMatch)
if(!backgroundMatch.save()) {
throw new RuntimeException("match is not valid and cannot be saved!")
}
})
我收到这个错误错误 events.PatchedDefaultFlushEventListener - 无法将数据库状态与会话同步
我们使用的是quartz 插件,效果很好。
我之前在不同的情况下遇到过同样的问题,解决方法是将域访问代码包装在
DomainClass.withTransaction {
}
例如:
def execute() {
Cal.withTransaction {
Cal.get(1).matches.each{
match ->
matchList.add(match)
}
for(Match m: matchList) {
if(!m.validate()) {
throw new MatchException( message: "match not valid!!" , match:m)
}
matchService.start(m)
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)