session的load和get方法都是从数据库中查找对应的数据,并转化为模型对象,在三种状态中属于persisent状态,但是他们之间有的十分大的区别:
GET:
当我们用session.get()方法时,hibernate直接发出sql语句查找到对应的数据并保存到Teacher对象当中,对象数据直接使用。
LOAD:
当我们用session.load()方法时,load生成的是Teacher对象的一个代理,而不是直接发出SQL语句取出Teacher对象,当改代理对象不使用时,hibernate不会进行任何数据库的交流,当对象使用时,如t.getName() ;才发出SQL语句进行查询,所以当用LOAD进行加载时候,所有的操作必须在session关闭之前进行,否则将会出现延迟错误现象:
13:32:29,766 ERROR LazyInitializationException:42 - could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:132)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:174)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.bjsxt.hibernate.vo.Teacher_$$_javassist_0.getName(Teacher_$$_javassist_0.java)
at HibernateIDTest.testLoad(HibernateIDTest.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
GET:
@Test
public void testGet(){
Session session = sessionFactory.getCurrentSession() ;
session.beginTransaction() ;
Teacher t = (Teacher)session.get(Teacher.class, 1) ;
session.getTransaction().commit() ;
}
当我们用session.get()方法时,hibernate直接发出sql语句查找到对应的数据并保存到Teacher对象当中,对象数据直接使用。
LOAD:
@Test
public void testLoad(){
Session session = sessionFactory.getCurrentSession() ;
session.beginTransaction() ;
Teacher t = (Teacher)session.load(Teacher.class, 1) ;
t.getName() ;
session.getTransaction().commit() ;
}
当我们用session.load()方法时,load生成的是Teacher对象的一个代理,而不是直接发出SQL语句取出Teacher对象,当改代理对象不使用时,hibernate不会进行任何数据库的交流,当对象使用时,如t.getName() ;才发出SQL语句进行查询,所以当用LOAD进行加载时候,所有的操作必须在session关闭之前进行,否则将会出现延迟错误现象:
@Test
public void testLoad(){
Session session = sessionFactory.getCurrentSession() ;
session.beginTransaction() ;
Teacher t = (Teacher)session.load(Teacher.class, 1) ;
session.getTransaction().commit() ;
t.getName() ;
}
13:32:29,766 ERROR LazyInitializationException:42 - could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:132)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:174)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.bjsxt.hibernate.vo.Teacher_$$_javassist_0.getName(Teacher_$$_javassist_0.java)
at HibernateIDTest.testLoad(HibernateIDTest.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)