Jils
Jils

Reputation: 783

Hibernate: deactivate the column version update for a specific save

I know it's possible to completely deactivate the version by setting the version to false:

class Book {
    …
    static mapping = {
        version false
    }
}

But is it possible to deactivate it only for a specific case?

Domain

class Book {
    String author 
}

Current behavior

def BookInstance = Book.get(1)
println "version $BookInstance.version" //version 1
BookInstance.author = 'John'
BookInstance.save(flush:true) 
println "version $BookInstance.version" //version 2

Specific case

def BookInstance = Book.get(1)
println "version $BookInstance.version" //version 1
//Do something to deactivate the update version
BookInstance.author = 'John'
BookInstance.save(flush:true) 
println "version $BookInstance.version" //version 1

Upvotes: 0

Views: 124

Answers (2)

Paulo Henrique
Paulo Henrique

Reputation: 56

I've never seen an option to disable temporarily optimistic locking.

If that's an option, you can execute a native update:

first inject the SessionFactory into the Service or Controller

def sessionFactory

then inside your method do something like this:

def sql = new Sql(sessionFactory.currentSession)
sql.execute("update BOOK set AUTHOR = 'john' where id = 1")

(I can't check the syntax right now, but it'll probably work)

Upvotes: 1

Michal_Szulc
Michal_Szulc

Reputation: 4177

I think you should look for alternative locking in hibernate:

Your application is forbidden from altering the version number set by Hibernate. To artificially increase the version number, see the documentation for properties LockModeType.OPTIMISTIC_FORCE_INCREMENT or LockModeType.PESSIMISTIC_FORCE_INCREMENT check in the Hibernate Entity Manager reference documentation.

If the version number is generated by the database, such as a trigger, use the annotation @org.hibernate.annotations.Generated(GenerationTime.ALWAYS).

Upvotes: 0

Related Questions