I know if a Grails service is transactional a call to save(flush: true)
can be rolled back. My question is if there is ever a need to call flush whilst in a service.

- 10,451
- 28
- 109
- 179
2 Answers
It depends on the working scenario. Ideally, it wont be necessary to flush every time you save something in the service class because the session gets flushed once returned back from the service class.
But think of a scenario where you have two different hibernate sessions working separately but data from one depends on another, then you would need to flush.
For example, Session 2 needs data read from db which frequently gets updated by Session 1 at the same time then that information has to be flushed to underlying persistence to make it available for session 2.
You can get granularity about how transactions can be handled by using @Transactional
in service class explicitly and specifying the Propagation/Isolation Strategy, if required.

- 49,365
- 7
- 88
- 117
-
If "the session gets flushed once returned back from the service class" then how would it be possible for data to not be available in the second session unless the sessions were some how nested? In the section `I am putting all my business code in services, am I safe?` in the article [here](http://blog.octo.com/en/transactions-in-grails/) there is an example where two services are called in the same controller method. I would expect that flushing would not be required from the first service call but the data would still always be available in the second. – ubiquibacon Aug 12 '13 at 16:06
-
Also, if you could provide a specific example (in code) when flushing would be required in a service I would appreciate it. – ubiquibacon Aug 12 '13 at 16:11
-
@ubiquibacon I mentioned particularly "at the same time" to make it clear. Two sessions reading or writing at the same time. The article you indicated is appropriate for two consecutive calls to two different services. I will add few code when I get some free time today. In the mean time have a look at this [question](http://stackoverflow.com/questions/6288991/do-i-ever-need-to-explicitly-flush-gorm-save-calls-in-grails). – dmahapatro Aug 12 '13 at 16:48
If you are doing bulk inserts using Hibernate then you will want to flush the Session periodically in order to prevent an OutOfMemoryException
as the Session will keep growing until it is flushed (and cleared). Flushing writes the objects queued in the Hibernate Session cache to the database (in other words, doing SQL inserts), but the inserts are within the scope of a DB transaction so they can be rolled back.
The Hibernate docs have further discussion on this topic.

- 22,503
- 19
- 75
- 98