Hibernate中g(shù)et()和load()的區(qū)別
作者:mamaoyuan625
本文將簡單談?wù)凥ibernate中l(wèi)oad和get的兩大區(qū)別,包括具體實踐的情況。作者最后認為效率上肯定是load()更高。
Hibernate中g(shù)et()和load()的區(qū)別
Java代碼
- Configuration cfg = new Configuration().configure();
- SessionFactory sf = cfg.buildSessionFactory();
- Session session = sf.openSession();
- Transaction tr = session.beginTransaction();
- Configuration cfg = new Configuration().configure();
- SessionFactory sf = cfg.buildSessionFactory();
- Session session = sf.openSession();
- Transaction tr = session.beginTransaction();Java代碼
- Pet pet = (Pet) session.load(Pet.class, 3);
- Pet pet = (Pet) session.load(Pet.class, 3); /**load:
* 控制臺并沒有打印任何select信息
* 1:返回的是代理對象 ,沒有真正的訪問數(shù)據(jù)庫
* 2:如果對象不存在訪問其屬性則拋出:ObjectNotFoundException異常
* 3: pet.getPetName();現(xiàn)在訪問pet對象的屬性,這樣才真正的訪問數(shù)據(jù)庫,
*/
Java代碼
- Configuration cfg = new Configuration().configure();
- SessionFactory sf = cfg.buildSessionFactory();
- Session session = sf.openSession();
- Transaction tr = session.beginTransaction();
- Configuration cfg = new Configuration().configure();
- SessionFactory sf = cfg.buildSessionFactory();
- Session session = sf.openSession();
- Transaction tr = session.beginTransaction();Java代碼
- Pet pet = (Pet) session.get(Pet.class, 3);
- Pet pet = (Pet) session.get(Pet.class, 3);
- /** get:
- * 控制臺有select語句
- * 1:用get() 總是會和數(shù)據(jù)庫交互
- * 2: pet.getPetName()
- * 如果此對象不存在訪問其屬性則拋出:java.lang.NullPointerException 異常
- */
效率上肯定是load 更高
【編輯推薦】
責(zé)任編輯:彭凡
來源:
javaeye