user2377549
user2377549

Reputation: 11

NHibernate Db Calls made in a web session

I have recently started working on a project using NHibernate as a ORM tool.I read about the contextual session in nHibernate and understood the idea behind it. I have a doubt in one area,

Let's say, i have a employee domain and in a http call,i am calling my repository for getting employee id =1 , 3 times.

Employee employee = _employeeRepository.GetEmployee(1);

Case 1: It will be a 1 db call Case 2: It will be 3 db calls.

please guide me on this.

rgds Sandy

Upvotes: 0

Views: 61

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65079

It depends on your setup.

The first level cache will hit the DB once against each Session object you use to query with. If there is a single Session shared with this repository.. only one DB call will be made. However, if each call to the repository causes more than one Session to be created, you'll get multiple calls. This is the default.

If the second level cache is enabled, then each Session created via a SessionFactory will share the above properties. Meaning, if you have multiple repositories with multiple Session's that came from the same SessionFactory instance.. then loading the same employee from both repositories will cause a single DB call.

There is some good information in this post - it is related to Hibernate, but the basic principles still apply to NHibernate.

I would recommend you enable a second level cache (we use SysCache2) in a web environment.. so that you can guarantee that the Session's always share cached objects within a single request (assuming of course, that your Session lifetime management is per-request.. which is should be..).

Upvotes: 1

Related Questions