Tutorial :Unreliable Hibernate Objects



Question:

I've run into a situation where the Hibernate object passed back from the query is unreliable.

Consider the following code:

MyClass myClass = myDAO.get(id);    myClass.getId(); //This works  myClass.getName(); //This returns null sometimes, and works sometimes  

Here's my get Method:

@SuppressWarnings("unchecked")  public T get(ID id)   {      Session s = getSession();      T entity = (T) s.load(getPersistentClass(), id);      s.disconnect();      return entity;  }  

Now, I understand that this object is a proxy, and will be lazy loaded, but I would expect it to either always work, or never work. Am I doing something wrong here?


Solution:1

This may or may not be the cause, but you probably shouldn't be using Session.load(), you should be using Session.get().

load() returns the persistent instance as currently loaded by hibernate, and it's possible this is partially populated depending on what happened before.

get() is more robust. Try that.


Solution:2

Problem is "load" will load a proxy of the object and not actually hit the database. However, if the object has already been loaded (and populated) i.e. in the level 1 cache, it will provision that instance.

When you use load, it will only actually hit the database when absolutely necessary, i.e. when you ask for one of the fields of the object.

Get on the other hand will actually hit the database.

For your purposes I would recommend that whether you use load or get you make sure the object is populated before passing it back. Before you pass it back, call one of the getters on it. Then you can guarantee that it is populated.

A useful exercise would be to enable sql logging (org.hibernate.SQL=DEBUG), debug through it and have a look at what sql instructions are being executed.

You could also consider configuring the persistent object you're loading to be non lazy. That way, whether you use load or get, you're going to get a fully populated object every time.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »