@Transactional
public MyEntity getEntity(long id) {
return dao.findOne(id);
//or select and update as well
}
Each time I call the transactional method: will I get any cached entity from hibernate (except for the first time)? Or will I always get the fresh entity fetched from DB?
This is important as I will have two independent apps that will share the same DB, and I want to ensure that hibernate does not return any cached entities while another app might have already updated the same entity in DB in the background.
If this is the transaction boundary for your service layer then Hibernate will create a new Session, meaning there's nothing in the first level cache. If you try to call the findOne
method twice within the same service method, the second call will fetch the entity from the cache.
Successive service method calls (e.g. getEntity) always end up with a new Hibernate Session, so a fresh entity is loaded from the database.
If you employ a 2nd level cache and activate it for this entity, then Hibernate will always hit the cache first and fallback to database loading, on a cache miss.
To prevent data integrity anomalies, consider using optimistic locking anyway.