懶載入例項--hibernate

瓜瓜東西發表於2014-04-19

其實在預設的時候不寫 就是懶載入的呢,只是些了更明確一些 laze=true/false 只有這兩個值,如果設定為false的話,就是load方法仍然會執行sql語句的,load和 lazy配合使用的

例項

1 設定為true

<?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.lyq.model.Medicine" table="tb_medicine_cache" lazy="true">
<id name="id">
<generator class="native"/>
</id>
<property name="name" not-null="true" length="200" />
<property name="price" not-null="true"/>
<property name="factoryAdd" length="200"/>
<property name="description" type="text"/>
</class>
</hibernate-mapping>

2 測試

package com.lyq.util;


 import org.hibernate.Session;


import com.lyq.model.Medicine;
/**
 * Lazy測試
 * @author Li Yong Qiang
 */
public class Test {
public static void main(String[] args) {
Session session = null; //宣告Session物件
//開啟第一個session
try {
//獲取Session
session = HibernateUtil.getSession();
//開啟事物
session.beginTransaction();
System.out.println("第一次查詢:");
//查詢藥品
Medicine medicine = (Medicine)session.load(Medicine.class, new Integer(1));
//提交事物
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
//出錯將回滾事物
session.getTransaction().rollback();
}finally{
//關閉Session物件
HibernateUtil.closeSession(session);
}
//開啟第二個session
try {
//獲取Session
session = HibernateUtil.getSession();
//開啟事物
session.beginTransaction();
System.out.println("============================================");
System.out.println("第二次查詢:");
//查詢藥品
Medicine medicine = (Medicine)session.load(Medicine.class, new Integer(1));
//輸出藥品名稱
System.out.println("藥品名稱:" + medicine.getName());
//提交事物
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
//出錯將回滾事物
session.getTransaction().rollback();
}finally{
//關閉Session物件
HibernateUtil.closeSession(session);
}
}
}


結果

第一次查詢:
============================================
第二次查詢:
Hibernate: 
    select
        medicine0_.id as id0_0_,
        medicine0_.name as name0_0_,
        medicine0_.price as price0_0_,
        medicine0_.factoryAdd as factoryAdd0_0_,
        medicine0_.description as descript5_0_0_ 
    from
        tb_medicine_cache medicine0_ 
    where
        medicine0_.id=?
藥品名稱:2

相關文章