Search code examples
hibernategrailsgrails-ormtransactional

Grails GORM locks table when updating a DB table


I am iterating over a large dataset and updating each row. The data locked as long as its loops and the changes are not saved until its all done

My Code:

In the controller

stocks.each { stock ->

        def s = stockService.updateData(stock)
        stockService.save s
    }

and the save method in the service is the only on with @Transactional:

@Transactional
private void save(Stock stock) {
    stock.save(failOnError: true, flush: true)
}

Solution

  • If you dont want that the datasets are locked the whole time, you can create a transaction for each save:

    private void save(Stock stock) {
        Stock.withNewTransaction {
            stock.attach()
            stock.save()
        }
    }
    

    The disadvantage is, that a rollback of all changed datasets is not possible on errors.