Not able to understand output while using get() and load() function in hibernate

I have a student table with the primary key id. I am using Hibernate and session's load command to fetch the record. The records I am fetching ids 1 and 2, are both not present in the database. I know that get() returns null in such cases and load() returns ObjectNotFoundException() in such cases. But I'm getting a strange output.

Student student1 = session.get(Student.class, 1);
System.out.println(student1);
Student student2 = session.load(Student.class, 2);
System.out.println("ABC");
System.out.println(student2);

The output I'm getting -

null
ABC
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [org.tutorial.Student#2]

The output I was expecting -

null
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [org.tutorial.Student#2]

Is there something I'm not getting here?


If you use session.load() to load an entity and that entity is not retrieved using session.get() in the same transaction before , it will return you an uninitialised proxy and it is its expected behaviour.

As the returned proxy is uninitialised , there are no DB access during the session.load() and hence it will not throws ObjectNotFoundException during that time even the ID is invalid.

It will only select the record from the DB to actually initialise the proxy if you access the entity 's properties other than its ID after that (1) . During initialising the proxy if it finds that there are no DB records exist for this ID , it will throw ObjectNotFoundException. Now you are accessing the student2 's properties through its toString() when you print it and hence ObjectNotFoundException is thrown at that time.

Also refer to my answers about 10 years ago about the differences between session.get() and session.load() at here.

Note (1) : The behaviour is actually defined by the configuration hibernate.jpa.compliance.proxy.Please see it for detail