79378141

Date: 2025-01-22 14:35:43
Score: 1
Natty:
Report link

Normally, all operation you do within a transaction will be cached in memory until you commit the transaction. This may use up a lot of memory or even cause an out-of-memory error. So you may make a flush to send all pending updates to the database. The database, however, will execute all queries but will not make them persistent until you commit the transaction. If memory isn't a problem, you usually do not need a flush.

There are, however, some situations where you might need to do it, as some operations may depend on the outcome of a previous one. So saving a new entity and then adding it as child to an existing one requires the new entity having an unique ID - but since the save wasn't actually executed, it hasn't one yet.

Usually Hibernate is clever enough to detect this and perform a flush on its own.

But if you e.g. just fetch the ID of the new entity after saving it and put it somewhere as number, you'll might get a NULL, as the save (and the assignment of an ID) wasn't done yet. If you call flush after the save, it suddenly gets an ID which you can read and use. Also, the Version field will be updated only when the query is sent, so if your code later (in the same transaction) checks an object's version to detect a change, it won't have changed (until flush).

If you code only does scarce changes on objects, you may also wrap each save or update (or block of those) into its own individual transaction.

Reasons:
  • Long answer (-1):
  • No code block (0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: Peter Painter