简体   繁体   中英

Grails flush: true inside Domain.withTransaction {} closure

This article says the following:

Product.withTransaction{
    product.status = "ACTIVE"
    product.save(flush:true) //without this line the total number will be all of them but this one
    Product.countByStatus("ACTIVE")
}

The unclear part is the following comment:

without this line the total number will be all of them but this one

and the explanation in the article right after the above code:

In the previous code without forcing flush:true we would have been omitting the product we were saving in our transaction.

As per my understanding, if we call product.save() (without flush) the product instance should be attached to Hibernate session, becoming a persistent entity, which should be included in the number returned by Product.countByStatus("ACTIVE") as the transaction is same where we have saved the product and hibernate session contains the info of that saved product even if the instruction is not flushed to database.

Usually the DB-session is flushed after the whole transaction block ( either with withTransaction{} , withSession{} or declarative demarcation) is finished.

flush:true makes the session be flushed immediately . That means that if you call product.save() the count*() method returns data BEFORE the session was flushed into the DB. The same behaviour you would get, if you call count*() after the transaction:

Product.withTransaction{
    product.status = "ACTIVE"
    product.save()
}
// here the TX shouldv'e been committed already
Product.countByStatus("ACTIVE")

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