.net c#在网络会话中进行的NHibernate Db呼叫

NHibernate Db Calls made in a web session
2021-03-07
  •  译文(汉语)
  •  原文(英语)

我最近开始使用NHibernate作为ORM工具进行项目开发.我了解了nHibernate中的上下文会话,并了解了其背后的思想.我在一个方面有疑问

假设我有一个员工域,并且在http调用中,我正在调用我的存储库以获取3位员工ID = 1.

雇员雇员= _employeeRepository.GetEmployee(1);

情况1:将是1分贝调用情况2:将是3分贝调用.

请为此指导我.

rgds桑迪

解决过程1

这取决于您的设置.

一级缓存将针对Session您用于查询的每个对象一次命中数据库.如果Session与此存储库共享一个共享库,那么将只进行一个数据库调用.但是,如果对存储库的每次调用导致Session创建了多个调用,则您将获得多个调用.这是默认值.

如果启用了二级缓存,则每个Session通过创建的缓存SessionFactory将共享上述属性.这意味着,如果您有多个存储库,其中多个存储库Session来自同一SessionFactory实例..则从两个存储库加载同一员工将导致一个数据库调用.

这篇文章中有一些很好的信息-与Hibernate有关,但是基本原理仍然适用于NHibernate.

我建议您在网络环境中启用二级缓存(我们使用SysCache2).这样您就可以保证Session始终在单个请求中共享缓存的对象(当然,假设您的Session生命周期管理是按请求进行的) ..应该是..).

速聊1:
感谢西蒙的移植

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

Solutions1

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..).

Talk1:
Thanks Simon's for your explantion
转载于:https://stackoverflow.com/questions/23027949/nhibernate-db-calls-made-in-a-web-session

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入