延迟加载又叫lazyload,在one-many many-many的时候都可以使用关系的延迟加载
- 修改配置文件 Category.hbm.xml
改为<set name="products" lazy="false">
表示通过Category获取产品是延迟加载的<set name="products" lazy="true">
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.how2java.pojo"> <class name="Category" table="category_"> <id name="id" column="id"> <generator class="native"> </generator> </id> <property name="name" /> <set name="products" lazy="true"> <key column="cid" not-null="false" /> <one-to-many class="Product" /> </set> </class> </hibernate-mapping>
- lazy=true的代码演示
执行15行的时候,只会查询Category表的信息,不会查询product_表
只有在执行18行,通过category取products的时候,才会进行对product_表的查询
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.how2java.pojo.Category; public class TestHibernate { public static void main(String[] args) { SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session s = sf.openSession(); s.beginTransaction(); Category c = (Category) s.get(Category.class, 1); System.out.println("log1"); System.out.println(c.getProducts()); System.out.println("log1"); s.getTransaction().commit(); s.close(); sf.close(); } }