Hibernate中get()和load()的区别
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:返回的是代理对象 ,没有真正的访问数据库
* 2:如果对象不存在访问其属性则抛出:ObjectNotFoundException异常
* 3: pet.getPetName();现在访问pet对象的属性,这样才真正的访问数据库,
*/
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() 总是会和数据库交互
- * 2: pet.getPetName()
- * 如果此对象不存在访问其属性则抛出:java.lang.NullPointerException 异常
- */
效率上肯定是load 更高
【编辑推荐】