javaEE Hibernate, 懒加载/延迟加载(类级别),session.load(),使用对象时才去执行sql查询

 

Test.java(类级别的延迟加载session.load()):

package cn.xxx.demo;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import cn.xxx.domain.Customer;
import cn.xxx.utils.HibernateUtils;

//懒加载|延迟加载
public class Test {
	
	@Test
	public void fun1(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		//----------------------------------------------------
		//get()方法:立即加载.执行方法时立即发送sql语句查询结果
		Customer c = session.get(Customer.class, 2l); // 根据id查询。
		
		System.out.println(c);
		//----------------------------------------------------
		tx.commit();
		session.close();		
	}
	
	@Test
	// load方法:是在执行时,不发送任何sql语句.返回一个对象.使用该对象时,才执行查询.
	// 延迟加载(懒加载): 仅仅获得没有使用,不会查询;在使用时才进行查询.
	// 是否对类进行延迟加载: 可以在Customer.hbm.xml配置文件中配置,class元素上配置lazy属性来控制是否延迟加载.
		//lazy:true(默认值)  加载时,不查询.使用时才查询
		//lazy:false 加载时立即查询.
	public void fun2(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		//----------------------------------------------------
		// load()懒加载。  Customer.hbm.xml配置文件中没有配置lazy="false" (采用默认值true)
		Customer c = session.load(Customer.class, 2l);
		
		System.out.println(c); // 在使用对象c时,才会执行sql查询。 查询依赖于绑定的session对象;首次使用对象,必须在session.close()之前。
		//----------------------------------------------------
		tx.commit();
		session.close();  // 在close()之后,首次使用对象c会报错。 (懒加载)
	}
}

Customer.hbm.xml(配置文件;类级别的懒加载配置)(一般采用默认配置):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.xxx.domain" >
	<class name="Customer" table="cst_customer" lazy="false" > <!-- lazy懒加载(类级别的延迟加载),默认"true"支持懒加载 -->
		<id name="cust_id"  >
			<generator class="native"></generator>
		</id>
		<property name="cust_name" column="cust_name" ></property>
		<property name="cust_source" column="cust_source" ></property>
		<property name="cust_industry" column="cust_industry" ></property>
		<property name="cust_level" column="cust_level" ></property>
		<property name="cust_linkman" column="cust_linkman" ></property>
		<property name="cust_phone" column="cust_phone" ></property>
		<property name="cust_mobile" column="cust_mobile" ></property>

		<set name="linkMens" batch-size="3"  >
			<key column="lkm_cust_id" ></key>
			<one-to-many class="LinkMan" />
		</set>
		
	</class>
</hibernate-mapping>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值