I’m a bit confused by the JavaDocs on Session.load:
Return the persistent instance of the given entity class with the given identifier, assuming
that the instance exists. This method might return a proxied instance that is initialized on-demand,
when a non-identifier method is accessed.You should not use this method to determine if an instance exists (use get() instead). Use this
only to retrieve an instance that you assume exists, where non-existence would be an actual error.
I understand I’m supposed to use get, but what I don’t understand is what is meant with the bit about it initialized on demand when a non-identifier method is used.
For me, if I have a class and use load(MyClass.class, NonExistingID), and then print the output of the getId() on the returned instance, it seems to automatically produce a new instance with NonExistingID every single time. Why is this?
I’m just trying to understand, is getId() a non-identifying method?
‘Non-identifier method’ means a method that returns something besides the identifier (as in primary key id) for the object.
loadgives you a proxy, where the proxy only queries the database once you ask it for something besides the identifier. SogetIdis an identifier method, Hibernate doesn’t query the database for its value (it doesn’t have to because you passed it into theloadmethod call).Found this snippet on the hibernate forums:
So it sounds like you have used load to get a proxy for a nonexistent object, but since you haven’t called any ‘nonidentifier methods’ on it, you haven’t forced the proxy to hit the database and haven’t gotten an error.