Hibernate筆記6(get和load)
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