如何解决不良的nHibernate集合初始化问题

and*_*era 2 .net nhibernate fluent-nhibernate nhibernate-criteria

nHibernate3; 从EAV数据模式中检索4xxx记录.当nHibernate或.NET第一次初始化这些集合时,我们看到了严重的惩罚.后续调用看起来效率更高.在SQL Server Management Studio中运行相同的查询会导致预期的快速返回时间.

使用Fluent和运行时映射代替.hbm.xml; 好奇,如果序列化的映射会有帮助吗?

nHibernate Profiler和log4net日志记录似乎没有让我继续下去.在这个过程中,总共有140,000个实体被水合.

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

尝试了加入和渴望fetchtypes,没有明显的结果,但我不是100%肯定我实现了这些 - 只是父母需要如此指定,还是子表也需要被标记?

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

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

这是花费大部分时间的地方:

return new ProductList(products.Select(p => p.ToProductContract()));
Run Code Online (Sandbox Code Playgroud)

这只是一个执行此操作的扩展方法:

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
                       };
        }
Run Code Online (Sandbox Code Playgroud)

映射:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

不幸的是,未来我似乎仍然得到了类似的结果.这是一个新的痕迹; 我现在已经切换到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();
Run Code Online (Sandbox Code Playgroud)

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_.ProductTypeID为ProductT1_6_0_,producttyp2_ .ProductTypeName as ProductT2_6_0_ FROM Product this_ inner join ProductType producttyp2_ on this_.ProductTypeId = producttyp2_.ProductTypeID;

SELECT 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_.AttributeID为Attribut6_2_1_,productatt0_ .ExpirationDateTime如Expirati7_2_1_,productatt0_.IsCurrentIndicator如IsCurren8_2_1_,productatt0_.OperationCode如Operatio9_2_1_,productatt0_.OperationDateTime如Operati10_2_1_,productatt0_.OperationSystemName如Operati11_2_1_,productatt0_.OperationUserName如Operati12_2_1_,productatt0_.LastUserPriority如LastUse13_2_1_,attribute1_.AttributeId如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_.Constraint 最大值为Constrai7_1_0_,attribute1_.ValuesMin为ValuesMin1_0_,attribute1_.ValuesMax为ValuesMax1_0_,attribute1_.Precision为Precision1_0_ FROM ProductAttribute productatt0_ inner join属性attribute1_ on productatt0_.AttributeID = attribute1_.AttributeId WHERE(productatt0_.IsCurrentIndicator = 1)和productatt0_.ProductId in(选择this_.ProductID FROM Product this_ inner join ProductType producttyp2_ on this_.ProductTypeId = producttyp2_.ProductTypeID)

选择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(选择this_. ProductID FROM Product this_ inner join ProductType producttyp2_ on this_.ProductTypeId = producttyp2_.ProductTypeID)

Flo*_*Lim 8

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

2)设置FetchMode需要应用于子节点,如下所示:

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

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

编辑:

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

// 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()));
Run Code Online (Sandbox Code Playgroud)