简体   繁体   English

有条件地获取关联实体避免 SELECT N+1 问题

[英]Conditionally fetching associated entity avoiding SELECT N+1 problems

Suppose I have the following domain:假设我有以下域:

public class Company
{
    public long Id;
}

public class EmployeeDetailsInCompany
{
    public long Id;
    public Company Company;
}

public class Employee
{
    public long Id;
    public List<EmployeeDetailsInCompany> EmployeeDetailsInCompany;
}

public class Position
{
    public long Id;
    public Employee Employee;
    public Company Company;
}

(Please note that this is a very simplified version to make the problem easier to understand.) (请注意,这是一个非常简化的版本,使问题更容易理解。)

Basically I want to access the EmployeeDetailsInCompany of the Employee I have in a Position entity.基本上,我想访问我在Position实体中拥有的EmployeeDetailsInCompanyEmployee Currently I have to loop through the list I have on Employee and find the EmployeeDetailsInCompany whose Company.Id match that of my Company entity.目前,我必须遍历我在Employee上的列表,并找到Company.Id与我的Company实体相匹配的EmployeeDetailsInCompany This is because a Position is only valid for a certain Employee on a certain Company , so that's where the EmployeeDetailsInCompany gets in.这是因为Position仅对某个Company的某个Employee有效,所以这就是EmployeeDetailsInCompany进入的地方。

The best option here would be to have an association between Position and EmployeeDetailsInCompany , but that's not possible because the data on that table can change (eg a company might decide to wipe out all of its employees details and load new data again).这里最好的选择是在PositionEmployeeDetailsInCompany之间建立关联,但这是不可能的,因为该表上的数据可能会发生变化(例如,公司可能决定清除其所有员工详细信息并再次加载新数据)。

Is it possible to rewrite those associations so I don't fall into SELECT N+1 problems (which is happening now that I have to loop through the list)?是否可以重写这些关联,这样我就不会陷入 SELECT N+1 问题(现在我必须遍历列表,这种情况正在发生)? How could I change it to make it easier to locate the details I want without much hassle?我该如何更改它,以便更轻松地找到我想要的详细信息,而不会有太多麻烦?

I have considered creating a EmployeeDetailsInCompany on Position that would be mapped using a formula, but that would give me a readonly column and I'm trying to avoid HQL.我曾考虑在Position上创建一个EmployeeDetailsInCompany ,该Position将使用公式进行映射,但这会给我一个只读列,我试图避免 HQL。

Read the chapter on improving performance in the reference documentation if you haven't done so.如果您还没有这样做,请阅读参考文档中有关提高性能的章节。 I think especially the section on batch fetching is relevant.我认为特别是关于批量获取的部分是相关的。 It means that NHibernate can fetch several potentially interesting database rows in one go, when you ask for one of them.这意味着当您请求其中之一时,NHibernate 可以一次性获取几个可能有趣的数据库行。

Another option is to write a specialized query that would generate SQL to let the DBMS do the work.另一种选择是编写一个专门的查询来生成 SQL 来让 DBMS 完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM