hibernate中get和load的区别

package com.wxh.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

import com.wxh.dto.Student;

public class Test {
	
	public static void main(String[] args) {
		
		Configuration cfg=new AnnotationConfiguration().configure();
		SessionFactory factory=cfg.buildSessionFactory();
		Session session=factory.openSession();	
//		Student stu=(Student)session.get(Student.class, 2);
		session.beginTransaction();
		Student stu=(Student)session.load(Student.class, 2);
		session.getTransaction().commit();
		session.close();		
		System.out.println(stu);//报错:could not initialize proxy - no Session
	}
}

/**
 * get和load的区别
 * 		get不支持延迟加载,通过get查询数据时,立即向数据库发送查询语句,
 * 如果被查询的数据在数据库不存在时则返回null;
 *      load方法默认支持延迟加载,通过load查询时,不会立即向数据库发送查询语句,
 * 只有当需要使用时被查询的数据时才会向数据库发起查询请求;如果被查询的数据不存在,
 * 会发生系统异常。如果使用延迟加载,在使用对象之前不能关闭session,否则就会出现no session异常。
 * 		
 * 
 */


也可以配置延迟加载


<?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="com.wxh.pojo">
	<!-- name对应类名称 -->
	<class name="Student" lazy="false">
		<!-- name对应属性名字 -->
		<id name="stuNo">				
			<generator class="native">
			<!-- 设置自定义序列的名字 -->
				<param name="sequence">auto_sid</param>
			</generator>
		</id>
		<property name="name" column="stuname" length="16" not-null="true" unique="false">
		</property>
		<property name="major" length="32"></property>
		<property name="comingYear"></property>
		<property name="type" length="16"></property>
	</class>
</hibernate-mapping>

改为false,直接加载。

lazy="false"




  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值