Daniel
Daniel

Reputation: 155

NHibernate session is not caching

I am relatively new for Nhibernate and I am having a problem caching the entities in the session( first level cache) Here is my code

public Book IProductRepository.GetBookbyName(string bookName)
{
        ISession session = NHibernateHelper.GetSession();
        ICriteria criteria = session.CreateCriteria<Book>()
                                     .Add(Restrictions.Eq("Name", bookName));
        return criteria.UniqueResult<Book>();
}

and

private static ISessionFactory _sessionFactory;

    private static ISessionFactory SessionFactory
    {
        get
        {
            if (_sessionFactory == null)
            {
                var configuration = new Configuration();
                configuration.Configure();
                configuration.AddAssembly(typeof(Product).Assembly);
                _sessionFactory = configuration.BuildSessionFactory();
                CurrentSessionContext.Bind(_sessionFactory.OpenSession());
            }
            return _sessionFactory;
        }
    }


    public static ISession GetSession()
    {
        return SessionFactory.GetCurrentSession();
    }

and the config file is

<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=(local);initial catalog=NhibernateTest;Integrated Security=SSPI</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name ="current_session_context_class">thread_static</property>
<property name="cache.use_query_cache" >true</property>
<property name="show_sql">true</property>

and everytime I call GetBookByName method, it hits the database no matter what? Thanks

Upvotes: 3

Views: 1274

Answers (1)

Dmitry
Dmitry

Reputation: 17350

NHibernate will not use first level cache when you query by something other than Id. In other words, Gets and Loads will look into first level cache, but ICriteria searching by Name will go to the database. You can use 2nd level NHibernate cache or implement your own caching.

As a side note you also seem to have a race condition at this line:

if (_sessionFactory == null)

Multiple threads can potentially see _sessionFactory as null and proceed to create it twice.

Upvotes: 4

Related Questions