Reputation: 714
I'm creating a service that has read-only access to the database. I have a query cache and a second level cache enabled (READ_ONLY mode) in Hibernate to speed up the service, as the tables being accessed change rarely.
My question is, if someone goes into the DB and changes the tables manually (i.e. outside of Hibernate), does the cache recognize automatically that it needs to be cleared? Is there a time limit on the cache?
Upvotes: 13
Views: 14100
Reputation: 570595
If you don't go through Hibernate APIs to make your changes, the second-level-cache won't get notified and the changes won't be visible. The usual way to deal with this situation is to evict the corresponding objects from the second-level-cache programatically to force a refresh. The SessionFactory
provides methods allowing to do this. From the section 19.3. Managing the caches of the documentation:
For the second-level cache, there are methods defined on
SessionFactory
for evicting the cached state of an instance, entire class, collection instance or entire collection role.sessionFactory.evict(Cat.class, catId); //evict a particular Cat sessionFactory.evict(Cat.class); //evict all Cats sessionFactory.evictCollection("Cat.kittens", catId); //evict a particular //collection of kittens sessionFactory.evictCollection("Cat.kittens"); //evict all kitten collections
Upvotes: 8
Reputation: 47994
Nope, the cache isn't going to scan the database for you to magically update itself when the underlying data changes. Changes that do not come through the L2 cache will not appear in it. How long it takes to time out etc. depends on your provider and whatever the default settings are. It looks like the default ehcache.xml is for 2 minutes.
Upvotes: 8