hibernate - 如何避免 "N+1 Select"并为具有多对一的 (N)Hibernate 用户类型指定获取策略?

标签 hibernate nhibernate nhibernate-mapping

我有一个具有多对一引用的复合组件。

class MyComposite
{
    SomeEntity ManyToOne { get; set; }
    SomeOtherUserType Value { get; set; }
}

为了便于映射,我做了一个自定义 ICompositeUserType其中包含此组件:
class MyCompositeUserType : ICompositeUserType
{
    // ...
    private static readonly IType[] _propertyTypes = new[]
                                   {
                                       new ManyToOneType("SomeEntity"), 
                                       new CustomType(typeof(SomeOtherUserType))
                                   };
    // ...
}

现在,我收藏了 composite-element s 包含此组件:

<class name="Container">
...
<set name="Pairings"
     cascade="all-delete-orphan"
     generic="true"
     lazy="false"
     table="Pairings"
     fetch="join">
    <key column="ContainerId" />
    <composite-element class="Pair">
        <property name="Item1" type="mycomposite" lazy="false">
            <column name="Entity1Id" />
            <column name="Amount1" />
        </property>
        <property name="Item2" type="mycomposite" lazy="false">
            <column name="Entity2Id" />
            <column name="Amount2" />
        </property>
        <property name="Tag" column="Tag" />
    </composite-element>
</set>
</class>

当我在 Container 上查询时类,Pairings set 被急切地加载,按照设计,但是,然后我在 SomeEntity 上得到了 N+1 选择它构成了 MyCompositeUserType 的一部分.我想加载这些实体以及 Pairings 上的连接。放。

如何指定?

最佳答案

如果映射为组件,您可以使用 lazy="false"将其映射为多对一,或者应该可以在查询时设置 fetchmode

<composite-element class="Pair">
    <component name="Item1">
        <many-to-one name="Entity1" column="Entity1Id" />
        <property name="Amount" column="Amount1" />
    </component>
    <component name="Item2">
        <many-to-one name="Entity2" column="Entity2Id"/>
        <property name="Amount" column="Amount2" />
    </component>
    <property name="Tag" column="Tag" />
</composite-element>

关于hibernate - 如何避免 "N+1 Select"并为具有多对一的 (N)Hibernate 用户类型指定获取策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10359957/

相关文章:

c# - 如何使用 FK NHibernate 映射复合 PK

c# - 使用 nHibernate 实体和 DTO 发送网格数据

java - 我们如何测试 JPA/Hibernate 中的 N+1 问题?

java - ContextLoader - 上下文初始化失败

java - Hibernate相关对象未水合

postgresql - 无法从 NHibernate.Driver.NpgsqlDriver 创建驱动程序

NHibernate.TypeMismatchException : Provided id of the wrong type. 预期 : System. Int32,得到 System.Int64

java - Spring 安全 : Error creating bean/No bean is defined

c# - Nhibernate QueryOver 左外连接条件

nhibernate - Fluent NHibernate 相当于一对一关系的逆向