You can also use refresh
to reload the entity. Or evict
and clear
, as mentioned by @Bozho.
With a connection pool, the overhead to open and close session isn't big. What takes time is to construct the session factory.
The problem with closing and re-opening a session is that object already loaded will still become detached, if I remember well. This can be problematic w.r.t to lazy loading. So it's better to keep the session open and use evict
, clear
or refresh
.
Note that if you evict the entity, and you access one such entity already loaded, you will still get the old data.
MyEntity e = session.load( ... );
...
session.evict(e); // remove entity from the cache
String p = e.myProperty; // still the value at the time it was loaded
e = sesssion.load( ... ); // latest value
In you case, it might be better to introduce a design guideline that says that anytime the entity is manipulated, it should be refreshed first.
MyEntity e = session.load( ... );
...
session.refresh( e ); // refresh entity and cache
String p = e.myProperty; // latest value
e = sesssion.load( ... ); // latest value
The code above is only pseudo-code, I haven't checked it.
Note that if the session is opened for a certain time, the cache may grow, in which case you may want to still clear
it. Generally speaking, it's however better to keep the session short to prevent this problem of cache growth, plus problems with connection timeout, transaction timeout, and lock contention.