<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="com.hyi.test.hibernate.model.Plu" table="plu">
<composite-id>
<key-property name="storeID" length="10" />
<key-property name="itemNumber" length="10" />
</composite-id> <property name="detail">
<column name="detail" length="3" />
</property>
</class> <class name="com.hyi.test.hibernate.model.Ord" table="ord">
<composite-id>
<key-property name="storeID" length="10" />
<key-property name="itemNumber" length="10" />
<key-property name="requestNumber" length="10" />
</composite-id>
<property name="detail">
<column name="detail" length="3" />
</property>
<many-to-one name="plu" cascade="none" outer-join="true"
fetch="join" lazy="false" insert="false" update="false"
class="com.hyi.test.hibernate.model.Plu">
<column name="storeID" />
<column name="itemNumber" />
</many-to-one>
</class></hibernate-mapping>
用上面的配置来查询
List list = session.createQuery("from Ord").list();
发现hibernate并没有用left join,用了n+1个sql语句才获得所有数据???

解决方案 »

  1.   

    如果使用hql的话必须用left join fetch 声明,因为不管你是不是在xml里面声明了out-join属性,用hql查询都会默认使用lazy load方式的
      

  2.   

    这是hibernate in action中的原话
    HQL always ignores the mapping document eager fetch (outer join) setting. If
    you’ve mapped some associations to be fetched by outer join (by setting
    outer-join="true" on the association mapping), any HQL query will ignore
    this preference. You must use an explicit fetch join if you want eager fetching
    in HQL. On the other hand, the criteria query will not ignore the mapping!
    If you specify outer-join="true" in the mapping file, the criteria
    query will fetch that association by outer join—just like Session.get() or
    Session.load() for retrieval by identifier. For a criteria query, you can
    explicitly disable outer join fetching by calling setFetchMode("bids",
    FetchMode.LAZY). HQL is designed to be as flexible as possible: You can
    completely (re)define the fetching strategy that should be used at runtime.