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"