简体   繁体   中英

Grails rollback withTransaction on save

I'm testing withTransaction but I got some problem. Why after I saved an object, I cannot rollback it? For example

Domain1 obj1 = new Domain(name: "obj1")
Domain1.withTransaction { status ->
    if(obj1.save(flush:true)){ //save the object, has no errors
        Domain2 obj2 = new Domain(name: asdasd) // making error happen
        if(!obj2.save(flush:true)){ // dont save, because its not string
            status.setRollbackOnly() // rollback the obj1
        }
    } else{
    throw new PersistenceException("error", obj1.errors)
    }
}

There's another way to roll back the save()?

When using transactions there are important considerations you must take into account with regards to how the underlying persistence session is handled by Hibernate. When a transaction is rolled back the Hibernate session used by GORM is cleared. This means any objects within the session become detached and accessing uninitialized lazy-loaded collections will lead to LazyInitializationExceptions.

To understand why it is important that the Hibernate session is cleared. Consider the following example:

class Author {
    String name
    Integer age

static hasMany = [books: Book] }

If you were to save two authors using consecutive transactions as follows:

Author.withTransaction { status ->
    new Author(name: "Stephen King", age: 40).save()
    status.setRollbackOnly()
}

Author.withTransaction { status -> new Author(name: "Stephen King", age: 40).save() }

Only the second author would be saved since the first transaction rolls back the author save() by clearing the Hibernate session. If the Hibernate session were not cleared then both author instances would be persisted and it would lead to very unexpected results.

It can, however, be frustrating to get LazyInitializationExceptions due to the session being cleared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM