1

I understand session.load() method in Hibernate.

Employee emp = (Employee) session.load(Employee.class, new Long(1));

Above will just return proxy, not hitting the database until any method is called on emp object.

I read that if i call identifier i.e. emp.getId(), then also no database call is made. But when I ran, it did call the database even though I have below in Employee class.

@Id
private Long id; 

Please let me know what I am doing wrong.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Anand
  • 20,708
  • 48
  • 131
  • 198
  • may be this links help: http://stackoverflow.com/questions/11228838/how-to-unproxy-a-hibernate-object http://stackoverflow.com/questions/13434636/elegant-way-of-unproxy-hibernate-objects – razon Sep 23 '14 at 16:25
  • getId() is also hitting database which should haven't been the case – Anand Sep 23 '14 at 16:44
  • I'm confused. What is your question again? – Zeus Sep 23 '14 at 16:50

1 Answers1

2

In order for getId() to not initialize the proxy, annotations must be put on getters, and not on fields.

If they're put on fields, as I understand it, Hibernate doesn't consider the getters as a way to access the persistent state of the entity (since it accesses the fields directly), but as methods that might do something other than simply returning the corresponding attribute. So the state is loaded before executing the method.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255