0
votes

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.

1

1 Answers

1
votes

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")