The session. Load/get method can read records from the database based on the specified object class and ID, and return the corresponding object. The difference is:
- If no matching record is found, the get method returns NULL, and the load method throws an objectnotfoundexception.
- The load method returns the proxy class instance of the object, while the get method returns the object class directly.
- The load method can make full use of the existing data in the internal cache and the second-level cache, while the get method only searches for data in the internal cache. If no corresponding data is found, the second-level cache will be crossed, directly call SQL to read data.
When a session loads an object, it goes through the following process:
- first, two levels of cache are maintained in hibernate. The first level of cache is maintained by the session instance, which maintains the data of all associated entities of the session, also known as the internal cache. The second-level cache exists at the sessionfactory level and is shared by all session instances constructed by the current sessionfactory. In order to avoid unnecessary database access for performance consideration, session queries in the cache before calling the database query function. First, in the first-level cache, the object type and ID are used for search. If the first-level cache query hits and the data status is valid, the system returns the result directly.
- then, the session searches for the current "nonexists" record. If the same query condition exists in the "nonexists" record, null is returned. "Nonexists" records the query conditions of the current session instance in all previous query operations, and the query conditions of valid data cannot be queried (equivalent to a query blacklist list ). In this way, if an invalid query condition reoccurs in the session, you can quickly make a judgment to obtain the best performance.
- for the load method, if no valid data is found in the internal cache, the second-level cache is queried. If the second-level cache hits, the second-level cache returns.
- if no valid data is found in the cache, select SQL is initiated. If no corresponding record is found after query, the query information is recorded in "nonexists" and null is returned.
- Create a Data Object Based on the resultset obtained by the ing configuration and select SQL.
- include the data objects in the current Session Object Management container (level-1 cache ).
- execute the Interceptor. onload method (if there is a corresponding interceptor ).
- include data objects in the second-level cache.
- If the data object implements the lifecycle interface, the onload method of the data object is called.
- return the data object.