• Post Reply Bookmark Topic Watch Topic
  • New Topic

Hibernate Session  RSS feed

Paresh Bhavsar
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I am new to hibernate. I will appreciate if someone will guide me on following.

i am returning my bean object persisted through hibernate back to servlet. i read that once i close my session it is detached and i can not access data from it. But surprisingly in my case it is not. WHY ? please find my code below. NewAccountBean i am accessing right in my jsp page and it is able to display the data too.

public NewAccountBean validateLogin(String cid, String pwd) {
boolean result;
Session session = SessionFactoryUtil.getInstance().openSession();
Transaction trans = session.beginTransaction();
NewAccountBean login = (NewAccountBean) session.load(NewAccountBean.class, new Long(Long.parseLong(cid)));
System.out.println("password from database" + login.getPwd());
if (pwd.equals(login.getPwd()))
result = true;
if (result)
return login;
return null;
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, when Hibernate loads a JavaBean, it loads all properties associated with that bean, so once the POJO is 'detached' from the Session, all of those properties of the bean are still available.

Also, any other POJOs that are associated with that bean through a one-to-one mapping will be loaded as well. So, all properties of a POJO, and all one-to-one associations are EAGERLY loaded by Hibernate.

One to Many and Many to Many relationships are loaded in a Lazy fashion, so, if you try and access properties of those beans, by default, you won't get them if the session is closed. You can, however, change the FetchType of an association and make it EAGER, and in that case, the associated objects WILL be loaded and available after the session is closed.

One design pattern is called "Open Session in View" where you keep the session open while the JSP is generating the view, thus eliminating LazyLoadedExceptions completely. It's advanced stuff.

Here's a little tutorial that's very popular about how Hibernate loads data, persists data, and manages data. You might find it interesting:

How Hibernate Works: Working with Hibernate and the Java Persistence API (JPA)

Keep asking questions, newbie! It's the best way to learn.

-Cameron McKenzie

  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!