2

nHibernate3; EAV データ スキーマから 4xxx レコードを取得します。nHibernate または .NET がこれらのコレクションを初めて初期化するとき、深刻なペナルティが発生します。後続の呼び出しは、より効率的に実行されるように見えます。SQL Server Management Studio で同じクエリを実行すると、返される時間が短くなることが予想されます。

.hbm.xml の代わりに Fluent およびランタイム マッピングを使用する。シリアル化されたマッピングがここで役立つかどうか知りたいですか?

nHibernate Profiler と log4net のログ記録では、あまり先に進むことができなかったようです。このプロセスでは、合計で 140,000 ほどのエンティティがハイドレートされます。

コレクションの初期化ペナルティを示す dotTrace パフォーマンス トレースのスクリーンショットを添付します。 遅い nHibernate コレクションの初期化の dotTrace

結合と熱心なフェッチタイプを試してみましたが、明らかな結果はありませんでしたが、それらを正しく実装したことを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 を使用しても、同様の結果が得られるようです。これが新しいトレースです。とりあえずリリースに切り替え、重要なプロジェクトでは 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 - .Future() を使用した、x64 をターゲットとするリリース モード

.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_.ProductType_ID を Product_typ6 として選択します。 .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 .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_Max.1Values として attribute1_Max.1Values として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_.ProductTypeID)ConstraintText as Constrain5_1_0_、attribute1_.ConstraintMin as Constrai6_1_0_、attribute1_.ConstraintMax as Constrai7_1_0_、attribute1_.ValuesMin as ValuesMin1_0_、attribute1_.ValuesMax as ValuesMax1_0_、attribute1_.Precision1_0_ FROM ProductAttribute productatt0_ inner join Attribute attribute1_ on productatt0_.AttributeID=attribute1_ (AttributeId=attribute1_. productatt0_.IsCurrentIndicator=1) および productatt0_.ProductId in (select this_.ProductID FROM Product this_ inner join ProductType producttyp2_ on this_.ProductTypeId=producttyp2_.ProductTypeID)ConstraintText as Constrain5_1_0_、attribute1_.ConstraintMin as Constrai6_1_0_、attribute1_.ConstraintMax as Constrai7_1_0_、attribute1_.ValuesMin as ValuesMin1_0_、attribute1_.ValuesMax as ValuesMax1_0_、attribute1_.Precision1_0_ FROM ProductAttribute productatt0_ inner join Attribute attribute1_ on productatt0_.AttributeID=attribute1_ (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 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 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_ として選択します。 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 のリストに変換していますか? その場合、子コレクションがループ内で DB から遅延ロードされているように見えます。

編集:

N+1 Select に対抗するには、NHibernate に事前にすべてを、できれば Futures でロードするように指示する必要があります。基本的に、少数の Select ステートメントを使用してデータベースからすべてのデータをフェッチする潜在的なソリューションを次に示します。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

1 つのオプションは、コレクションでバッチサイズを有効にすることです。それらは怠惰であり、バッチサイズが有効になっていると、1回のラウンドトリップで複数のエンティティのコレクションをフェッチしようとします。

1 つのコレクションで 1 つのエンティティを取得しても違いはありませんが、すべてが 1 つのコレクションを持つ 1000 個のエンティティを選択すると、大きな違いが生じる可能性があります。1000 のバッチサイズを使用すると、1001 ではなく 2 つのクエリが発生します。

いくつかのドキュメントを見つけようとしましたが、次の例しか見つかりませんでした:

nhibernate はバッチ サイズを変更します

あなたのケースで結合戦略を使用すると、結果セットが巨大になるため、これは適切なオプションではありません。より良いオプションは、コレクションを後続のラウンドトリップで明示的にロードする FetchMode.Select を使用することです。

パフォーマンスを向上させることができるもう 1 つのことは、次の設定です。

Session.FlushMode = FlushMode.Never;

スコープの自動フラッシュを無効にします。これは、実際にデータを変更するのではなく、読み取るだけである場合に便利です。ただし、IsDirty への呼び出しや、コールスタック内のダーティ オブジェクトのその他のチェックが表示されます。

于 2011-04-18T15:01:15.837 に答える
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 に答える