Search code examples
databasegrailspessimistic-locking

Grails Pessimistic locking with executeUpdate()


I can't find any info on how to use pessimistic locking with an executeUpdate() command in grails. Is this possible?

[Update] As per Burt's suggestion, this is the resulting query I have. Note that I have used the deprecated UPGRADE instead PESSIMISTIC_WRITE since this option is not there.

def session = sessionFactory.currentSession
def query = session.createQuery("UPDATE SensorProcessed s SET s.batch=:batch WHERE s.device.id=:deviceId AND s.batch.id=:batchId AND s.sensor.id=:sensorId AND s.rollupKey=:rollupKey")
    query.setLockMode ("s", LockMode.UPGRADE)
    query.setParameter("batch",ignored)
    query.setParameter("deviceId",device.id)
    query.setParameter("batchId",batch.id)
    query.setParameter("sensorId",sensor.id)
    query.setParameter("rollupKey",rollupKey)
    def updatedRows = query.executeUpdate()

Thanks,
Abraham.


Solution

  • It's not supported, but it's simple enough to get access to the Hibernate API and use it there. Add a dependency injection for the session factory to your service or controller:

    def sessionFactory
    

    and then in your method replace the executeUpdate call with a regular Hibernate update:

    def session = sessionFactory.currentSession
    def query = session.createQuery("your HQL")
    query.setLockMode alias, LockMode.PESSIMISTIC_WRITE
    // set query variable values
    query.executeUpdate()