Hibernate笔记6(get和load)

来源:互联网 发布:自学编程难不难 编辑:程序博客网 时间:2024/06/05 19:23

session.load()和session.get()

load
Object load(Class theClass,
            Serializable id)
            throws HibernateExceptionReturn the persistent instance of the given entity class with the given identifier, assuming that the instance exists. This method might return a proxied instance that is initialized on-demand, when a non-identifier method is accessed.

You should not use this method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.

Parameters:
theClass - a persistent class
id - a valid identifier of an existing persistent instance of the class
Returns:
the persistent instance or proxy
Throws:
HibernateException

get
Object get(Class clazz,
           Serializable id)
           throws HibernateExceptionReturn the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. (If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance.)

Parameters:
clazz - a persistent class
id - an identifier
Returns:
a persistent instance or null
Throws:
HibernateException

load与get的区别
1.load返回的是一个代理,get返回一个原对象的实例;
 @Test
 public void testLoad() {
  Session session = sessionFactory.getCurrentSession();
  session.beginTransaction();
  Notes note = (Notes)session.load(Notes.class, 6);
  session.getTransaction().commit();
  System.out.println(note.getFileName());
 }
 
 @Test
 public void testGet() {
  Session session = sessionFactory.getCurrentSession();
  session.beginTransaction();
  Notes note = (Notes)session.get(Notes.class, 6);
  session.getTransaction().commit();
  System.out.println(note.getFileName());
 }
这两个方法执行后,testGet()可以正确执行,而testLoad()会抛出如下异常:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session


2.load是在对象已经存在的假设前提下的,所以对于一个不存在的id,load不会出错,会
返回一个代理,只有当这个代理被使用的时候才会报错,抛出如下异常:
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.cat.model.Notes#1]
get方法则会在get被调用的时候抛出:
java.lang.NullPointerException

原创粉丝点击