2

n休眠3; 从 EAV 数据模式中检索 4xxx 条记录。当 nHibernate 或 .NET 第一次初始化这些集合时,我们看到了严重的惩罚。随后的调用似乎更有效地执行。在 SQL Server Management Studio 中运行相同的查询会导致预期的快速返回时间。

使用 Fluent 和运行时映射而不是 .hbm.xml;好奇序列化映射是否会有所帮助?

nHibernate Profiler 和 log4net 日志记录似乎并没有给我太多帮助。在这个过程中,总共有大约 140,000 个实体被水合。

附上我的 dotTrace 性能跟踪的屏幕截图,显示集合初始化惩罚: 慢 nHibernate 集合初始化的 dotTrace

尝试过 join 和 eager fetchtypes,但没有明显的结果,但不能 100% 确定我正确地实现了这些 - 是否只需要如此指定父级,还是需要标记子表?

var products = ((HandleSession)_handleSession).Session.CreateCriteria(typeof(Product))
                    .SetFetchMode("Product", FetchMode.Eager)
                    .List<Product>()
                    .AsEnumerable();

通过 web.config 启用反射优化器(我认为): 启用反射优化器

这是花费最多时间的地方:

return new ProductList(products.Select(p => p.ToProductContract()));

这只是一个扩展方法:

public static ProductContract ToProductContract(this Product product)
        {
            return new ProductContract
                       {
                           Name = product.ProductName,
                           ProductTypeName = product.ProductType.ProductTypeName,
                           UpdateTimeStamp = product.UpdateDateTime,
                           ProductNumber = product.ProductNumber,
                           Attributes = product.ProductAttributes.ToCommonAttribute().ToList(),
                           GroupCategories = product.ProductGroups.ToGroupCategory().ToList(),
                           PublicUniqueId = product.PublicUniqueId
                       };
        }

映射:

internal class ProductMapping : ClassMap<Product>
    {
        private const string _iscurrentindicator = "IsCurrentIndicator=1";

        public ProductMapping()
        {
            Table("Product");
            Id(Reveal.Member<Product>("ProductId")).GeneratedBy.Identity().Column("ProductID");
            Map(x => x.ProductNumber).Column("ProductNumber").Not.Nullable();
            Map(x => x.ProductName).Column("ProductName").Not.Nullable();
            Map(x => x.InsertDateTime).Column("InsertedDateTime").Nullable().ReadOnly();
            Map(x => x.UpdateDateTime).Column("UpdatedDateTime").Nullable();
            Map(x => x.PublicUniqueId).Column("ProductGUID").Generated.Insert();

            References(x => x.ProductType).Column("ProductTypeId").Not.Nullable();
            HasMany(x => x.ProductAttributes)
                .KeyColumn("ProductId")
                .Inverse()
                .Fetch
                .Subselect()
                .Where(_iscurrentindicator)
                .Cascade
                .SaveUpdate();

            HasMany(x => x.ProductGroups).KeyColumn("ProductId").Fetch.Subselect().Where(_iscurrentindicator);
            DynamicUpdate();
            DynamicInsert();
            BatchSize(500);
        }
    }

internal class ProductGroupMapping : ClassMap<ProductGroup>
    {
        public ProductGroupMapping()
        {
            Table("ProductGroup");
            Id(x => x.ProductGroupId).Column("ProductGroupId").GeneratedBy.Identity();
            References(x => x.Product).Column("ProductId").Not.Nullable();
            References(x => x.Group).Column("GroupId").Not.Nullable();
            //Where("IsCurrentIndicator=1");
        }
    }

internal class ProductAttributeMapping : ClassMap<ProductAttribute>
    {
        public ProductAttributeMapping()
        {
            Table("ProductAttribute");
            LazyLoad();
            Id(x => x.ProductAttributeId).GeneratedBy.Identity().Column("ProductAttributeID");
            References(x => x.Product).Column("ProductID").Not.Nullable();
            References(x => x.Attribute).Column("AttributeID").Not.Nullable().Fetch.Join();
            Map(x => x.PositionNumber).Column("PositionNumber").Nullable();
            Map(x => x.ValueText).Column("ValueText").Nullable();
            Map(x => x.ValueBinary).Column("ValueBinary").Nullable();

            Component(x => x.OperationalAuditHistory, m =>
                        {
                            Table("ProductAttribute");
                            m.Map(x => x.ExpirationDateTime).Column("ExpirationDateTime").Nullable();
                            m.Map(x => x.IsCurrent).Column("IsCurrentIndicator").Not.Nullable();
                            m.Map(x => x.OperationCode).Column("OperationCode").Nullable();
                            m.Map(x => x.OperationDateTime).Column("OperationDateTime").Nullable();
                            m.Map(x => x.OperationSystemName).Column("OperationSystemName").Nullable();
                            m.Map(x => x.OperationUserName).Column("OperationUserName").Nullable();
                            m.Map(x => x.LastUserPriority).Column("LastUserPriority").Nullable();
                        });

            DynamicInsert();
            BatchSize(50);
        }
    }

不幸的是,使用 .Future 我似乎仍然得到了类似的结果。这是一个新的踪迹;我已经切换到Release,关键项目暂时切换到x64,所以时间更短,但比例仍然几乎相同;以及.Eager:

var products = ((HandleSession) _handleSession).Session.CreateCriteria(typeof (Product))
                    .SetFetchMode("ProductAttribute", FetchMode.Join)
                    .SetFetchMode("ProductGroup", FetchMode.Join)
                    .SetFetchMode("ProductType", FetchMode.Join)
                    .Future<Product>()
                    .AsEnumerable();

dotTrace - 发布模式,针对 x64,使用 .Future()

生成的带有 .Eager 和 .Future 的 SQL:

选择 this_.ProductID 作为 ProductID0_1_, this_.ProductNumber 作为 ProductN2_0_1_, this_.ProductName 作为 ProductN3_0_1_, this_.InsertedDateTime 作为 Inserted4_0_1_, this_.UpdatedDateTime 作为 UpdatedD5_0_1_, this_.ProductGUID 作为 ProductG6_0_1_, this_.ProductTypeId 作为 ProductT7_0_1_, producttyp2_0_,_productType2 作为 ProductT .ProductTypeName as ProductT2_6_0_ FROM Product this_inner join ProductType producttyp2_ on this_.ProductTypeId=producttyp2_.ProductTypeID;

选择 productatt0_.ProductId 作为 ProductId2_,productatt0_.ProductAttributeID 作为 ProductA1_2_,productatt0_.ProductAttributeID 作为 ProductA1_2_1_,productatt0_.PositionNumber 作为 Position2_2_1_,productatt0_.ValueText 作为 ValueText2_1_,productatt0_.ValueBinary 作为 ValueBin4_2_1_,productatt0_.ProductID 作为 ProductID2_1_,productatt0_.AttributeID0 作为 Attri2_1_ .ExpirationDateTime as Expirati7_2_1_, productatt0_.IsCurrentIndicator as IsCurren8_2_1_, productatt0_.OperationCode as Operatio9_2_1_, productatt0_.OperationDateTime as Operati10_2_1_, productatt0_.OperationSystemName as Operati11_2_1_, productatt0_.OperationUserName as Operati12_2_1_, productatt0_.LastUserPriority as LastUse13_2_1_, attribute1_.AttributeId as Attribut1_1_​​0_, attribute1_.AttributeName 作为 Attribut2_1_0_,attribute1_.DisplayName 作为 DisplayN3_1_0_,attribute1_.DataTypeName 作为 DataType4_1_0_,attribute1_.ConstraintText 作为 Constrai5_1_0_,attribute1_.ConstraintMin 作为 Constrai6_1_0_,attribute1_.ConstraintMax 作为 Constrai7_1_0_,attribute1_.ValuesMin 作为 ValuesMin1_0_,attribute1_.Values_Max 作为 ValuesPrecisions 作为_0_ Precision1_0_ FROM ProductAttribute productatt0_ inner join Attribute attribute1_ on productatt0_.AttributeID=attribute1_.AttributeId WHERE (productatt0_.IsCurrentIndicator=1) and productatt0_.ProductId in (select this_.ProductID FROM Product this_ inner join ProductType producttyp2_ on this_.ProductTypeId=producttyp2_.ProductTypeID)ConstraintText 作为 Constraint5_1_0_,attribute1_.ConstraintMin 作为 Constrai6_1_0_,attribute1_.ConstraintMax 作为 Constrai7_1_0_,attribute1_.ValuesMin 作为 ValuesMin1_0_,attribute1_.ValuesMax 作为 ValuesMax1_0_,attribute1_.Precision 作为 Precision1_0_ FROM ProductAttribute productatt0_inner join Attribute attribute1_ on productatt0_.AttributeID=attribute1_ productatt0_.IsCurrentIndicator=1) 和 productatt0_.ProductId in (select this_.ProductID FROM Product this_ inner join ProductType producttyp2_ on this_.ProductTypeId=producttyp2_.ProductTypeID)ConstraintText 作为 Constraint5_1_0_,attribute1_.ConstraintMin 作为 Constrai6_1_0_,attribute1_.ConstraintMax 作为 Constrai7_1_0_,attribute1_.ValuesMin 作为 ValuesMin1_0_,attribute1_.ValuesMax 作为 ValuesMax1_0_,attribute1_.Precision 作为 Precision1_0_ FROM ProductAttribute productatt0_inner join Attribute attribute1_ on productatt0_.AttributeID=attribute1_ productatt0_.IsCurrentIndicator=1) 和 productatt0_.ProductId in (select this_.ProductID FROM Product this_ inner join ProductType producttyp2_ on this_.ProductTypeId=producttyp2_.ProductTypeID)精度为 Precision1_0_ FROM ProductAttribute productatt0_ inner join Attribute attribute1_ on productatt0_.AttributeID=attribute1_.AttributeId WHERE (productatt0_.IsCurrentIndicator=1) 和 productatt0_.ProductId in (select this_.ProductID FROM Product this_ inner join ProductType producttyp2_ on this_.ProductTypeId=producttyp2_。产品类型 ID)精度为 Precision1_0_ FROM ProductAttribute productatt0_ inner join Attribute attribute1_ on productatt0_.AttributeID=attribute1_.AttributeId WHERE (productatt0_.IsCurrentIndicator=1) 和 productatt0_.ProductId in (select this_.ProductID FROM Product this_ inner join ProductType producttyp2_ on this_.ProductTypeId=producttyp2_。产品类型 ID)

选择 productgro0_.ProductId 作为 ProductId1_,productgro0_.ProductGroupId 作为 ProductG1_1_,productgro0_.ProductGroupId 作为 ProductG1_3_0_,productgro0_.ProductId 作为 ProductId3_0_,productgro0_.GroupId 作为 GroupId3_0_ FROM ProductGroup productgro0_ WHERE (productgro0_.IsCurrentIndicator=1) 和 productgro0_.ProductId in (select this_. ProductID FROM Product this_inner join ProductType producttyp2_ on this_.ProductTypeId=producttyp2_.ProductTypeID)

4

3 回答 3

8

1) 序列化映射只会有助于减少构建 SessionFactory 所需的时间。如果上面的查询不是第一次访问数据库,那么它不会在这方面完成任何事情。

2)设置FetchMode需要应用到孩子,像这样:

var products = ((HandleSession)_handleSession).Session.CreateCriteria(typeof(Product))
                .SetFetchMode("ProductChildren", FetchMode.Eager)
                .List<Product>()
                .AsEnumerable();

3) 如果我正确解释了屏幕截图中的方法,这看起来像一个 N+1 问题。您是否将Products查询结果中的 转换为 ProductDTO 列表?如果是这样,似乎子集合是在循环中从数据库中延迟加载的。

编辑:

为了对抗 N+1 Select,我们必须告诉 NHibernate 预先加载所有内容,最好使用 Futures。这是一个潜在的解决方案,它基本上使用一些选择语句从数据库中获取所有数据。我没有包含任何 Where 条件。那些你必须相应地添加。

// any where-condition will have to be applied here and in the subsequent queries
var products = session.QueryOver<Product>()
    .Future();

var products2 = session.QueryOver<Product>()
    .Fetch(p => p.ProductType).Eager
    .Future();

var products3 = session.QueryOver<Product>()
    .Fetch(p => p.ProductAttributes).Eager
    .Future();

var products4 = session.QueryOver<Product>()
    .Fetch(p => p.ProductGroups).Eager
    .Future();

// Here we execute all of the above queries in one roundtrip.
// Since we already have all the data we could possibly want, there is no need
// for a N+1 Select.
return new ProductList(products.Select(p => p.ToProductContract()));
于 2011-04-16T00:18:47.630 回答
1

如果您将此会话仅用于报告,则必须使用无状态会话: http: //nhforge.org/blogs/nhibernate/archive/2008/10/30/bulk-data-operations-with-nhibernate-s-stateless -sessions.aspx

于 2011-04-20T05:03:29.127 回答
1

一种选择是在您的集合上启用批量大小。我假设这些是惰性的,并且启用批量大小后,它会尝试在一次往返中获取多个实体的集合。

如果您使用一个集合获取 1 个实体并没有什么不同,但如果您选择 1000 个实体都具有一个集合,则可能会产生巨大的差异。使用 1000 的批量大小将导致 2 个查询而不是 1001 个。

试图找到一些文档,但只找到了这个例子:

nhibernate 交替批量大小

在您的情况下使用连接策略会产生巨大的结果集,因此这不是一个好的选择。更好的选择是使用 FetchMode.Select 它将明确强制您的集合在后续往返中加载。

可以提高性能的另一件事是设置:

Session.FlushMode = FlushMode.Never;

这会禁用范围的自动刷新。如果您实际所做的只是读取数据而不是修改数据,这将很有用。但是,您会看到对 IsDirty 的调用或对调用堆栈中脏对象的任何其他检查。

于 2011-04-18T15:01:15.837 回答