This is a design question, concrete code not submitted to protect my bottom.
When working with Hibernate the standard workflow is as follows:
Ad. A: Looks like you are aware what clear()
does. The reason to call it explicitly is to remove all managed entities from L1 cache, so that it does not grow infinitely when processing large data sets in one transaction.
It discards all the changes that were made to managed entites not explicitly persisted. This means that you can safely modify an entity, update it explicitly and clear the session. This is the right design. Obviously if no changes are made (long, but read only session), clear()
is always safe.
You can also use stateless sessions.
Ad. B: No, it exists for the reasons above: to make sure L1 (session cache) does not grow too much. Of course maintaining it manually is a poor idea and an indication that another tool should be used for large data sets, but sometimes it is a must.
Note that in JPA specification there is also clear()
and flush()
method. In this case you should always call flush()
first to push changes into the database (explicit update) prior to calling clear()
.
Ad. C: It's actually a good idea to warn the user (maybe by issuing warning message rather than throwing an exception) when he/she clears the session with dirty changes. Also I don't think a framework code should call clear()
unconditionally, unless it is sure that the user code it runs flushes or does not make any changes.