Combating the Select N + 1 Problem In NHibernate

本文探讨了使用NHibernate框架时常见的Select N+1问题,并提供了几种解决方案,包括通过单次查询获取所有数据的方法。

Source link: http://ayende.com/Blog/archive/2006/05/02/CombatingTheSelectN1ProblemInNHibernate.aspx

 

Combating the Select N + 1 Problem In NHibernate

 

Using an O/RM can greatly simplify your life, but is has its on set of Gotcha that you need to be aware of. One of the more serious ones is the Select N + 1 issue. To describe the issue, let's look at a typical example. Users א M:M א Blogs א 1:M א Posts א 1:M א Comments. Here is the diagram:

I hope that both my notation above and diagram makes it clear what the relations between the objects are (isn't class designer cool)? As an aside, the above model is from NHibernate.Generics tests. All collections are lazy.

I want to show the user all the comments from all the posts, so they can delete all the nasty comments. The naןve implementation would be something like:

foreach (Post post in blog.Posts)

{

    foreach (Comment comment in post.Comments)

    {

        //print comment...

    }

}

The posts collection has 80 posts in it. When we access it, we load all the posts (1 select to grab all the posts), now, when we access each post's Comments' collection, we need to issue a new select to get the data (1 select to grab all the comments for this post). In my testing, I got 81 selects from this seemingly innocent piece of code. I'm not sure about you, but I'm usually motivated to reduce the number of external queries. To put it another way, for every iteration of the external loop above, we have a database query. And that is in order to print a fairly simple UI, and this is a fairly common task.

There are several ways to solve the issue. The easiest is to just ask NHibernate to give you it all in a single query, like this:

IList posts = session.CreateQuery(

        @"from Post post left join fetch

        post.Comments where post.Blog = :blog")

    .SetEntity("blog",blog)

    .List();

foreach (Post post in posts)

{

    foreach (Comment comment in post.Comments)

    {

        //print comment...

    }

}

This code is a little more explicit in what it does; it tells NHibernate "give me all the posts for this blog, and make sure to fetch all their comments as well, since I'm going to use this". The result of this query is a single SQL Statement to load all the data in one go.

 

Fetch Join vs. Join

One important thing that you should be aware of is the difference between join fetch and just join. NHibernate can use multiply joins in a single statement, but can fetch only a single collection – it can fetch several properties {many to one or one to one} – in a single query. Fetching means that NHibernate will load the collection and put it in its proper place (for instance, load all the comments for this post and put them in the collection).

Normal joining means that NHibernate will return the correct objects, but it will not be able to associate them to their proper place in the objects without going to the database again.

To clarify, the result of this query:

IList  blogs = session.CreateQuery(

        @"from Blog blog left join fetch

        blog.Posts left join blog.Users

        where blog.id = 1")

    .List();

It is not a Blog object with all its collections already filled. It is a list of tuples { { blog1, user1} , { blog1, user2}, { blog1, user3},{ blog1, user1} }, etc. The list in my case has a length of 567, and contains many duplicate items. The reason it contains duplicate items is that NHibernate doesn't attempt to uniqueify (is that a word?) the result from the database, and because the database returned  567 (for all permutations of a post, blog and user), this is what you get. NHibernate is smart enough to return the same instances, so it is not a problem to do the filtering yourself.

However, if we will try to access the Users' collection of the blog that was returned, we will still get a query to the database to get the collection. NHibernate is smart enough to figure out that it already has the data itself in memory, so it will just ask for the identifiers and nothing more.

 

There are other ways to get the same result, we can use the Criteria API (my favorite), to do the same:

session.CreateCriteria(typeof(Post))

    .SetFetchMode("Comments", FetchMode.Eager)

    .Add(Expression.Eq("Blog", blog))

    .List();

This is one of the more powerful features on NHibernate, since it allows you a fine grained control of the loading strategy, based on your scenario. A fairly simple change turned an 80+1 queries (for a small example. If I was using my own blog for example, I would need ~1300+1 queries to get the data!!) to a single query.

And I can do this on a case by case basis! That is truly powerful.  

The other ways that I mentioned are no as fined grained, and involve changing the mapping for the specified association(s). This is good if you need to change the behavior for all the application in one stroke. Personally, I can't think of hand on many cases where I would need that, but it is good to have the option for when I would need it.

By Ayende @ Rahien

【事件触发一致性】研究多智能体网络如何通过分布式事件驱动控制实现有限时间内的共识(Matlab代码实现)内容概要:本文围绕多智能体网络中的事件触发一致性问题,研究如何通过分布式事件驱动控制实现有限时间内的共识,并提供了相应的Matlab代码实现方案。文中探讨了事件触发机制在降低通信负担、提升系统效率方面的优势,重点分析了多智能体系统在有限时间收敛的一致性控制策略,涉及系统模型构建、触发条件设计、稳定性与收敛性分析等核心技术环节。此外,文档还展示了该技术在航空航天、电力系统、机器人协同、无人机编队等多个前沿领域的潜在应用,体现了其跨学科的研究价值和工程实用性。; 适合人群:具备一定控制理论基础和Matlab编程能力的研究生、科研人员及从事自动化、智能系统、多智能体协同控制等相关领域的工程技术人员。; 使用场景及目标:①用于理解和实现多智能体系统在有限时间内达成一致的分布式控制方法;②为事件触发控制、分布式优化、协同控制等课题提供算法设计与仿真验证的技术参考;③支撑科研项目开发、学术论文复现及工程原型系统搭建; 阅读建议:建议结合文中提供的Matlab代码进行实践操作,重点关注事件触发条件的设计逻辑与系统收敛性证明之间的关系,同时可延伸至其他应用场景进行二次开发与性能优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值