I am aware of the fact that Session
is first level
The first-level (session level) cache ensures that the state of the persistent instances loaded by one transaction is isolated from the changes made by other transactions.
So the changes made by s2
in a different transaction(T2) is not visible when you call s1.get(User.class, 1)
in the first transaction, because this time Hibernate will fetch the User
from the session level cache s1
.
You'll need to call Session.evict(Object) on s1
with u1
as an argument in order to get a fresh lookup. Alternatively, for this case, you could also call Session.clear() on s1
as well to get the same effect. You could also call Session.refresh(Object object) to just refresh the state of u1
as well.
Note that transactions can take an undefined amount of time (usually not very long though) to be seen by other clients after they are committed. The update may not be visible immediately to other sessions using different connections.
No, Hibernate doesn't do anything to synchronize state of the entities in session cache with the DB, unless you request it explicitly.
Usually it's not a problem, because active work usually happens inside a transaction, and operations inside a transaction are not supposed to see changes made by other concurrent transactions (details depend on isolation level, though). So, behavior of Hibernate complements the typical semantics of transaction isolation in this case.
There can also be situations when state of the entity need to be explicitly synchronized to reflect changes made inside the same transaction. It may be caused by bulk update queries or execution of database triggers. In this case you need to request such a synchronization explicitly by calling refresh()
.