Grails transaction setSavePoint method on mysql ca

2019-07-20 15:06发布

问题:

I am using grails with mysql 5. I am using .withTransaction for transaction management in a service. Within the withTransaction block I am using savePoint() method which is causing the following exception. Note: I am using setRollbackOnly() method without any issue.

2011-06-26 23:02:37,818 [quartzScheduler_Worker-7] ERROR listeners.ExceptionPrinterJobListener  - Exception occured in job: GRAILS_JOBS.com.exmp.bdg.PowerRollupJob
org.quartz.JobExecutionException: Transaction manager does not allow nested transactions [See nested exception: org.springframework.transaction.NestedTransactionNotSupportedException: Transaction manager does not allow nested transactions]
    at org.codehaus.groovy.grails.plugins.quartz.GrailsJobFactory$GrailsTaskClassJob.execute(GrailsJobFactory.java:81)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:199)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:546)
Caused by: org.springframework.transaction.NestedTransactionNotSupportedException: Transaction manager does not allow nested transactions
    at org.springframework.jdbc.datasource.JdbcTransactionObjectSupport.getConnectionHolderForSavepoint(JdbcTransactionObjectSupport.java:151)
    at org.springframework.jdbc.datasource.JdbcTransactionObjectSupport.createSavepoint(JdbcTransactionObjectSupport.java:104)
    at org.springframework.transaction.support.AbstractTransactionStatus.createSavepoint(AbstractTransactionStatus.java:176)
    at org.springframework.transaction.SavepointManager$createSavepoint.call(Unknown Source)
    at com.exmp.bdg.service.PowerRollupService$_doRollup_closure2.doCall(PowerRollupService.groovy:85)

回答1:

By default the transaction manager for hibernate and MySQL don't have the save points enabled.

In BootStrap.groovy add the following:

transactionManager.setNestedTransactionAllowed(true)

Then in a transaction you can do the following:

Thing.withTransaction { status ->
  //Do some work and a save
  def savePoint = status.createSavepoint()
  //do other work
  if(checkOk)
  {
    //Everything worked so don't need the save point anymore
    status.releaseSavepoint(savePoint)
  }
  else
  {
    //The other work did not work so rollback from it.
    status.rollbackToSavepoint(savePoint)
  }

}