Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing session, flushing, refreshing, after hibernate bulk updates?

As we know, when doing a bulk update to the DB with hibernate (even in HQL), the changes made are not replicated to the entities stored in the current session.

So i may call session.refresh to load the modifications to my session entities.

We often call flush for sending our modifications to the DB, but the documentation say it "synchronize" the session and the db...

Does that mean that flush will be able to set the good new db value to my session entity? Or flush will eventually erase my new db value with the old one stored in the entity? (Btw if hibernate's behaviour is the 1st one, how does it detect which one is the "good value"?).

If i can't use flush on such a case, it is a good practice to clear the session after each bulk update so that we are sure to have good values in our session?

like image 227
Sebastien Lorber Avatar asked Oct 13 '11 16:10

Sebastien Lorber


People also ask

What is flush and clear in hibernate?

Manual, the programmer is informing hibernate that he/she will handle when to pass the data to the database. Under this configuration the session. flush() call will save the object instances to the database. A session. clear() call acutally can be used to clear the persistance context.

When should I flush hibernate?

By default, Hibernate uses the AUTO flush mode which triggers a flush in the following circumstances: prior to committing a Transaction. prior to executing a JPQL/HQL query that overlaps with the queued entity actions. before executing any native SQL query that has no registered synchronization.

Does flush close the session?

Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database).

What is session clear in hibernate?

Session. clear() This method is used to completely clear the session. Evict all loaded instances and cancel all pending saves, updates, and deletions.


1 Answers

All flush will do is sending previously cached SQL statements to the database. It will not change your objects that are already in session. In a way it does opposite to what you need. SQL statements from flush may, potentially, override your bulk update changes. What you probably want to do is flush() and then clear() before your update. Or, if you don't want to clear the entire cache, evict(). I never tried refresh() but it seems that it will also work.

like image 88
Alex Gitelman Avatar answered Nov 16 '22 03:11

Alex Gitelman