首页 > 代码库 > hibernate学习5_session之load与get区别

hibernate学习5_session之load与get区别

hibernate从数据库中查询对应记录到java实体中时,一般可通过session.load或者session.get来完成

(1)load方法

        @Test    public void testLoad(){        Session session1 = sf.getCurrentSession();        session1.beginTransaction();        Student t = (Student) session1.load(Student.class, 45);        System.out.println(t.getAge());        session1.getTransaction().commit();            }

在session关闭前使用返回对象时,hibernate加载正常

Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from Student student0_ where student0_.id=?

如果将调用去掉。如下

    @Test    public void testLoad(){        Session session1 = sf.getCurrentSession();        session1.beginTransaction();        Student t = (Student) session1.load(Student.class, 45);        //System.out.println(t.getAge());        session1.getTransaction().commit();            }

则hibernate执行上述程序时没有调用查询语句。

如果将调用放在session关闭之后,如下

    @Test    public void testLoad(){        Session session1 = sf.getCurrentSession();        session1.beginTransaction();        Student t = (Student) session1.load(Student.class, 45);        session1.getTransaction().commit();        System.out.println(t.getAge());            }

则出现如下异常

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
.....

(2)get方法

    @Test    public void testGet(){        Session session1 = sf.getCurrentSession();        session1.beginTransaction();        Student t = (Student) session1.get(Student.class, 45);        session1.getTransaction().commit();                System.out.println(t.getAge());    }

get方法返回对应对象后,无论是在session关闭前调用或者关闭后调用,都能正常进行查询

Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from Student student0_ where student0_.id=?

get方法返回对应对象后,即使不调用对象,依然能够正常查询。

 

综上:

(1)session的load方法返回对象时不是立即从数据库中执行查询,而是采用动态代理,在对象中属性被调用时hibernate再执行查询,即所谓的延迟加载。

     如果此时session关闭,则出现加载异常。

(2)session的get方法则是在返回对象时立即从数据库中执行对应查询,将返回记录封装进对应实体中

 

hibernate学习5_session之load与get区别