Fluent NHibernate对数千个对象执行单行选择以链接到父对象

时间:2009-04-21 09:12:45

标签: nhibernate fluent-nhibernate

以下是我的问题域的简化。我们有一系列交易,每个工作日都会在估值中获得记录。

我们过滤了特定日期使用的评估列表,但是针对每个评估行填充交易,NHibernate触发单个行在交易表中选择评估表中约50k行。我怎样才能改变这一点,以便NHibernate在Trade表上做一个选择?

CREATE TABLE Trades
(   TradeId         INT
,   InstrumentType  VARCHAR(20)
,   TradeDate       DATETIME

,   PRIMARY KEY
(   TradeId )   )

CREATE TABLE Valuations
(   TradeId         INT
,   ValueDate       DATETIME
,   PresentValue    NUMERIC(12,4)

,   PRIMARY KEY
(   TradeId
,   ValueDate   )   )

class Trade
{
    public int TradeId;
    public string InstrumentType;
    public DateTime TradeDate;
}

class Valuation
{
    public int TradeId;
    public DateTime ValueDate;
    public double PresentValue;
    public Trade Trade;
}   

class ValuationMap : ClassMap<Valuation>
{
    public ValuationMap()
    {
        WithTable("Valuations");
        UseCompositeId()
            .WithKeyProperty(x => x.ValueDate)
            .WithKeyProperty(x => x.TradeId);

        Map(x => x.PresentValue);

        References(x => x.Trade, "TradeId")
            .LazyLoad()
            .Cascade.None()
            .NotFound.Ignore()
            .FetchType.Join();
    }
}

class TradeMap : ClassMap<Trade>
{
    public TradeMap()
    {
        WithTable("Trades");

        Id( x => x.TradeId );

        Map(x => x.InstrumentType);
        Map(x => x.TradeDate);
        Map(x => x.Valuations);
    }
}

public List<Valuation> GetValuations(DateTime valueDate)
{
    return (from p in _nhibernateSession.Linq<Valuation>()
            where p.ValueDate == valueDate
            select p).ToList();
}

1 个答案:

答案 0 :(得分:1)

您还应该查看批量提取。这是来自Nhib manual - 实际上谷歌的缓存,因为该网站似乎因维护问题而停机:

  

想象一下,你有以下几点   运行时的情况:你有25只猫   每个都在一个ISession中加载的实例   Cat提及其所有者,a   人。 Person类已映射   使用代理,lazy =“true”。如果你现在   迭代所有的猫,然后得到   每个人的所有者,NHibernate将通过   默认执行25个SELECT语句,   检索代理所有者。您   可以通过指定a来调整此行为   Person的映射中的批量大小:

<class name="Person" lazy="true" batch-size="10">...</class>
  

NHibernate现在只执行三次   查询,模式是10,10,5。你   可以看出批量提取是盲目的   猜测,就性能而言   优化去,它取决于   a中的单元化代理数量   特别是ISession。