Hibernate first level cache - does it Sync?

后端 未结 3 743
广开言路
广开言路 2021-01-05 19:53

I am aware of the fact that Session is first level

相关标签:
3条回答
  • 2021-01-05 20:45

    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.

    0 讨论(0)
  • 2021-01-05 20:47

    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.

    0 讨论(0)
  • 2021-01-05 20:54

    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().

    0 讨论(0)
提交回复
热议问题