Hibernate lazy loading implementation principle


    Enable lazy loading of entities by setting the lazy property of the class to true.
If we run the following code:
User user=(User)session.load(User.class,"1"); (1)   
System.out.println(user.getName()); (2)
When running to (1 ), Hibernate did not initiate a query for the data. If we use some debugging tools (such as Eclipse's Debug tool) to observe the memory snapshot of the user object at this time, we will be surprised to find that what is returned at this time may be Object of type User$EnhancerByCGLIB$$bede8986, and its property is null, what's going on? The session.load() method will return the proxy class object of the entity object, and the object type returned here is the proxy class object of the User object. In Hibernate, a proxy class object of a target object is dynamically constructed by using CGLIB, and the proxy class object contains all the properties and methods of the target object, and all properties are assigned to null. Through the memory snapshot displayed by the debugger, we can see that the real User object at this time is contained in the CGLIB$CALBACK_0.target property of the proxy object. When the code runs to (2), user.getName( ) method, then through the callback mechanism given by CGLIB, the CGLIB$CALBACK_0.getName() method is actually called. When this method is called, Hibernate will first check whether the CGLIB$CALBACK_0.target property is null, if not, then Call the getName method of the target object. If it is empty, it will initiate a database query and generate an SQL statement like this: select * from user where id='1'; to query the data, construct the target object, and assign it to CGLIB $CALBACK_0.target property.
    In this way, through an intermediate proxy object, Hibernate realizes the lazy loading of entities, and only when the user actually initiates the action to obtain the properties of the entity object, will the database query operation be initiated. Therefore, the lazy loading of the entity is done through the intermediate proxy class, so only the session.load() method will use the entity lazy loading, because only the session.load() method will return the proxy class object of the entity class.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326564493&siteId=291194637