In application I have a reference table called Cycles that is mapped to Cycle entity. Basically most of mapped with NHibernate entities keep references to that table. Usually these entities have fields like:
- StartCycle
- ModificationCycle
- EndCycle
- Cycle
etc.
Even though I use session per request I still see in logs that majority of queries are issued to Cycles table. This is the case when I query not by Cycle ID, but by other properties that belong to Cycle type.
Cycle type is almost immutable, it has Status property, and actually this is the only property that can be changed by Service classes (like CloseCycleService, Open etc…).
Also Cycle cannot be deleted, but can be inserted.
So I would like to minimize the number of queries to Cycles table.
I could cache it inside ASP .NET by using application cache, and create another layer of abstraction, but before I do it I would like to know that are the options given by NHibernate and what are the drawbacks?
The only problem that I see is multithreading – even though Cycle is almost immutable (and stateless) it could happen that two requests try to modify the same entity at the same time and it could cause an error. But… it is almost impossible.
So could you advice what can I do with NHibernate to store all content of Cycles table in cache (oh, I also didn’t mention that the number of data in that table is small: 1 cycle per month, so currently it’s about 20rows, and will grow 1row per month) and minimize queries that are issued to Cycles table?
Use the NHibernate second level cache with the SysCacheProvider and query cache – when you create a query for your Cycle entity, call .SetCacheable(true) which will store the results of the query in the cache (as well as the entity itself)
NHibernate’s second level cache is very well implemented and will keep the cache consistent with any changes you make in the same process. If you are making changes directly in the database, then you can look at the SysCacheProvider2 (I think) which I believe has support for SqlDependencies also.