Hibernate 消極式載入,lazy屬性配置。以及org.hibernate.LazyInitializationException

來源:互聯網
上載者:User
<hibernate-mapping>    <class name="modle.Customers" table="customers" >        <id name="id" type="java.lang.Integer">            <column name="id" />            <generator class="identity" />        </id>        <property name="name" type="java.lang.String">            <column name="name" not-null="true" />        </property>        <set name="orderses" inverse="true" cascade="save-update" >            <key>                <column name="customer_id"  />            </key>            <one-to-many class="modle.Orders" />        </set>           </class></hibernate-mapping>

這是一對多,就是一個 Customers 對應 多個 order


下面是多對一的一方:

<hibernate-mapping>    <class name="modle.Orders" table="orders" catalog="h_01">        <id name="id" type="java.lang.Integer">            <column name="id" />            <generator class="identity" />        </id>        <many-to-one name="customers" class="modle.Customers" fetch="select" lazy="false">            <column name="customer_id"  />        </many-to-one>        <property name="orderName" type="java.lang.String">            <column name="orderName" not-null="true" />        </property>    </class></hibernate-mapping>


重要配置解釋:

1、inverse 就是反向,是說這種關聯關係是對對方控制的,就是many的一方。

inverse="true"

2、lazy  就是是否消極式載入。就是我在需要的時候才去載入,不需要不去載入。

在session關掉後,我們就不能再載入了。

就是常見的: org.hibernate.LazyInitializationException

這時,我們把lazy設為false。

lazy有兩種配置方法:

1) 在many-to-one 或 set 中配置:

  <set name="orderses" inverse="true" cascade="save-update" lazy="true">

在one的一方,lazy有3個值:false,true,extra。 預設是true。

消極式載入有很大好處,可以節省sql語句。

在many的一方,lazy有3個值:false,proxy,no-proxy。 注意這裡沒有true的選項。

一般在查詢many的一方時,也會查詢one的一方。

2) 在class中配置 :

在class上的lazy只對普通屬性起作用,什麼set,list統統不起作用,所以set 之類的還要再寫




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.