I love this place!
Well, if you were to compare the load and get methods of the Hibernate Session, you'd think that they looked pretty darned similar; and you'd be correct, but there are subtle and very important differences.
First of all, the get method hits the database as soon as it is called. So, using the Hibernate Session's get method will always trigger a database hit. On the other hand, the load method only hits the database when a particular field of the entity is accessed. So, if we use the load method to retrieve an entity, but we never actually access any of the fields of that entity, we never actually hit the database. Pretty kewl, eh?
Well, actually, as kewl as the load method might sound, it actually triggers more problems than it solves, and here's why. If you initialize a JavaBean instance with a load method call, you can only access the properties of that JavaBean, for the first time, within the transactional context in which it was initialized. If you try to access the various properties of the JavaBean after the transaction that loaded it has been committed, you'll get an exception, a LazyInitializationException, as Hibernate no longer has a valid transactional context to use to hit the database.
So, while this code will work just fine?..
session.beginTransaction();
User user=(User)session.load(User.class, new Long(1));
System.out.println(user.getPassword());
session.getTransaction().commit();
.. this code will fail ?..
session.beginTransaction();
User user=(User)session.load(User.class, new Long(1));
session.getTransaction().commit();
System.out.println(user.getPassword());
.. and generate the following error, telling you that since the transaction was committed, there was no valid Session in which a read transaction against the database could be issued:
org.hibernate.LazyInitializationException:
could not initialize proxy - no Session
So, the big thing to take away from this is that with the load method, you can't really use your loaded JavaBeans after the transaction has been committed, whereas, with the get method you can, because all of the various properties of a JavaBean retrieved through the get method are initialized right away.
try {
instance = new AppUser();
instance = (AppUser) getSession().get(
"com.itcentrix.altcp.Security.AppUser", id);
AppUser appUser = new AppUser();
instance = appUser.lazyInitialize(instance);
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
finally
{
getSession().flush();
// getSession().close();
// HibernateSessionFactory.closeSession();
}
return instance;
then it have any Disadvantage for sessions remaining open