I'm trying to create some threads in a service, but I got the hibernateException: no session... . I have already seen a discussion about this in stackoverflow with a solution of throwing RuntimeException. In my case is not working. Here is my service code:
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 } } job class:
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
With backgroundThread plugin (that should handle 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!") } }) I get this error ERROR events.PatchedDefaultFlushEventListener - Could not synchronize database state with session