Trt Trt
Trt Trt

Reputation: 5532

When and how does Hibernate flush its session?

I do not understand how hibernate session.flush() works. In grails when is it called if called automatically and how does it decide when is the best time to flush ? What if a user has done some actions that require thousands of queries, to be run at the end of his session? Multiply that by thousand of users.

Anything that you can share that explains session of hibernate in grails? Thanks

Upvotes: 2

Views: 923

Answers (1)

Joshua Moore
Joshua Moore

Reputation: 24776

Grails follows the "Open session in view" pattern of handling Hibernate sessions and automatic flushing.

In your example if you don't explicitly call .flush() on the session or use flush: true when modifying data it will in fact flush all the queries for the users session when the thread that started session ends (typically at the end of an HTTP request in a web based Grails application).

Depending on your application, it may make sense to flush the session periodically. Again, this depends heavily upon your application and how much data is being effected by a single user request. Flushing too frequently will kill performance as well.

If your concern is about performance, there is only one true way to determine what the best approach is. Profile your application using various approaches and see which suits your application.

Some additional information found in the Grails documentation regarding this topic:

A useful feature of Hibernate over direct JDBC calls and even other frameworks is that when you call save or delete it does not necessarily perform any SQL operations at that point. Hibernate batches up SQL statements and executes them as late as possible, often at the end of the request when flushing and closing the session. This is typically done for you automatically by Grails, which manages your Hibernate session.

Hibernate caches database updates where possible, only actually pushing the changes when it knows that a flush is required, or when a flush is triggered programmatically. One common case where Hibernate will flush cached updates is when performing queries since the cached information might be included in the query results. But as long as you're doing non-conflicting saves, updates, and deletes, they'll be batched until the session is flushed. This can be a significant performance boost for applications that do a lot of database writes.

Note that flushing is not the same as committing a transaction. If your actions are performed in the context of a transaction, flushing will execute SQL updates but the database will save the changes in its transaction queue and only finalize the updates when the transaction commits.

Upvotes: 4

Related Questions