Reputation: 4460
I'm using FluentNhibernate
version 2.0.3.0
and I'm trying to configure the cache of it to use with queries
, I'm using HQL
. I want to one opinion if I did all configurations alright, and I want to know how could I see if cache was activate ?
Connection
FluentConfiguration _config = Fluently.Configure()
.Database(
MySQLConfiguration.Standard.ConnectionString(
x => x.Server(HOST)
.Username(USER)
.Password(PASSWORD)
.Database(DB)))
.Cache(c => c.ProviderClass(typeof(NHibernate.Cache.HashtableCacheProvider).AssemblyQualifiedName)
.UseQueryCache())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<UsuarioMap>())
.ExposeConfiguration(cfg => new SchemaUpdate(cfg)
.Execute(false, true));
Mapping
public class UsuarioMap : ClassMap<Usuario> {
public UsuarioMap() {
Table("USUARIOS");
Cache.ReadWrite();
Id(u => u.id).GeneratedBy.Native();
Map(u => u.nome).Not.Nullable().Length(50);
Map(u => u.email).Unique().Not.Nullable().Length(255);
Map(u => u.senha).Not.Nullable();
Map(u => u.status).CustomType<int>();
Map(u => u.dtCadastro).CustomType<DateTime>();
Map(u => u.dtLastLogin).CustomType<DateTime>();
Map(u => u.tipo).CustomType<int>();
Map(u => u.imagem);
Map(u => u.loginBy).CustomType<int>();
Map(u => u.idFacebook);
}
}
HQL Query
public class UsuarioDAO : GenericDAO<Usuario>{
/** retorna todos os objetos */
public IList<Usuario> findAll(){
ISession _session = getSession();
IList<Usuario> list = _session.CreateQuery("FROM Usuario u ORDER BY u.nome")
.SetCacheable(true).SetCacheMode(CacheMode.Normal)
.List<Usuario>();
return list;
}
Upvotes: 0
Views: 884
Reputation: 9854
A UseSecondLevelCache
call is very likely missing (xml configuration parameter cache.use_second_level_cache
).
HashtableCacheProvider
is not intended for production use, only for test. Choose another one.
Transactions do not seem used. At first data change done outside of a transaction, the second level cache will be disabled. Better transacted all session usages.
A cache.default_expiration
should be configured. This is an integer, in seconds.
You may use session statistics to check if the cache is used. Enable them on the session factory.
sessionFactory.Statistics.IsStatisticsEnabled = true;
// Do your stuff then consult the statistics on the session factory.
Avoid letting them enabled in production, this incurs some overhead.
Additional notes:
If you have some mapped collection you wish to cache, you will have to enable caching for them in their mapping.
Caching works better with lazy-loading. Eager loading may cause cached entities to be reloaded from database instead of being loaded from cache.
Upvotes: 1