【问题标题】:Hibernate decide which fetching strategy to use at runtimeHibernate 决定在运行时使用哪种获取策略
【发布时间】:2012-11-09 07:25:52
【问题描述】:

我有一个关于 hibernate 的急切和延迟加载的问题。 我有以下设置:

public Person {
  int prsnId;
  Set<Preferences> preferences;
  Set<ContactDetails> contactDetails;

  //constructor

  //getters & setters
}

休眠映射:

<hibernate-mapping>
    <class name="be.bene.cris2.protocol.Person" table="BENE_CUST_PERSON" dynamic-update="true" dynamic-insert="true">
        <id name="prsnId" type="int">
            <column name="PRSN_ID" precision="10" scale="0" />
             <generator class="sequence">
                   <param name="sequence">CUST_PROR_SEQ</param>
            </generator>
        </id>
    <set access="field" name="preferences" table="PRSN_PREF" inverse="true">
        <key column="PRSN_ID" not-null="true"/>
        <one-to-many class="Preferences" not-found="ignore"/>
    </set>
    <set access="field" name="contactDetails" table="CNTCT_DETAILS" inverse="true">
        <key column="PRSN_ID" not-null="true"/>
        <one-to-many class="ContactDetails" not-found="ignore"/>
    </set>
    </class>
</hibernate-mapping>

现在,当我执行以下查询时,我想知道是否可以在运行时决定,例如,应该预先加载首选项,但应该延迟获取 contactDetails,或者有时根本不获取。

Criteria criteria = session.createCriteria(Person.class);
    criteria.setFirstResult(startRow)
        .setMaxResults(pageSize)
        .add(Restrictions.eq("prsnId", id))
        .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
    ;
List<Person> personList = criteria.list();

提前致谢。

【问题讨论】:

    标签: hibernate fetch hibernate-criteria


    【解决方案1】:

    您可以使用获取关联

    criteria.setFetchMode("preferences", FetchMode.JOIN);
    

    在这种情况下,首选项将与人员一起在同一个查询中获取,并且联系人详细信息将被延迟获取(这意味着只有在您调用联系人详细信息集上的方法时才会获取它们) .

    然而,问题在于连接提取不适用于setFirstResult()setMaxResults(),因为它们直接应用于 SQL 语句,因此用于设置由SQL 查询。而一个人,如果偏好是连接获取的,则对应于多行(每个偏好一行)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-03
      • 2016-02-18
      • 1970-01-01
      • 2010-10-11
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      相关资源
      最近更新 更多