Java – how to prevent hibernate from refreshing in the list?
I have a simple hibernate query, such as:
from MyEntity where name = ?
It's not fancy, but it's called many times in a fairly large transaction (lasting for a second, dozens or hundreds of entities may be loaded) Profiler display takes a lot of time:
org.hibernate.internal.SessionImpl.autoFlushIfrequired(SessionImpl.java:1185) org.hibernate.internal.SessionImpl.list(SessionImpl.java:1240) org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
In other words – refresh the changes before running the actual query
Can I prevent hibernate from completing this flushing in some way?
If not, what can I do to make it faster?
Solution
By default, hibernate will refresh before issuing queries during the session (flushmode. Auto), and it will consume a lot of CPU time It can be particularly painful if you run many queries and updates alternately in your session
These refreshes are required if the query may choose to insert / update / delete fallback data during the current session This can happen even if you do not modify anything in the current transaction, but use the transaction isolation level (such as read uncommitted)
Assuming you don't want uncommitted reads, etc., I know there are two solutions:
>Before making any changes, select everything you need during the session (that is, reorder to issue all queries before making any changes). > If you are sure you want to select data that has not been modified in this session, you can explicitly set the flush mode to content that will not trigger a refresh, as follows:
Query query = session.getNamedQuery(SOME_QUERY_NAME); query.setFlushMode(FlushMode.COMMIT);