Quote:
Why not use the persistence context in this instance?
I don't think this is as easy as you might think. The goal for such a functionality would of course be to return an identical result weather or not the session has been flushed before the query.
For simple queries only involving a single entity class it might be possible. Then, consider more complex queries involving joins, aggregate functions, grouping, order by, etc. Even if it was possible to search in the persistence context the result would then have to be merged with the result from executing the same query on the database. The merge would of course have to consider entities that have been updated in the persistence context but not yet flushed to the database. I just think it is a too complex task to be possible to implement.
I agree that the AUTO flush mode may be inefficient and we are using the MANUAL mode ourselves. In my case I discovered this when we needed a batch update functionality that could updated several thousands of items from a text file. Each item had to be found in the database using a query. It was fast to begin with but slowed down considerably after a few thousand items. The reason was that Hibernate was spending most of the CPU time with automatic dirty checking on all previously loaded objects as part of the flush that happened before each execution of the query. The best solution for us was to use the MANUAL flush mode and then flush and commit everything when all objects had been updated.