What's the advantage of load() vs get() in Hibernate?

前端 未结 10 2751
感情败类
感情败类 2020-12-02 04:58

Can anyone tell me what\'s the advantage of load() vs get() in Hibernate?

10条回答
  •  广开言路
    2020-12-02 05:13

    When Load is called it returns a Proxy object. Actual select query is still not fired. When we use any of the mapped property for the first time the actual query is fired. If row does not exist in DB it will throw exception. e.g.

    Software sw = ( Software )session.load(Software.class, 12);
    

    Here sw is of proxy type. And select query is not yet called. in Eclipse debugger you may see it like

    sw Software$$EnhancerByCGLIB$$baf24ae0  (id=17) 
       CGLIB$BOUND         true 
       CGLIB$CALLBACK_0 CGLIBLazyInitializer  (id=23)   
       CGLIB$CALLBACK_1 null    
       CGLIB$CONSTRUCTED    true    
       id                  null 
       prop1               null 
       softwareprop        null 
    

    when I use

     sw.getProp1()
    

    the select query is fired. And now proxy now knows values for all the mapped properties.

    Where as when get is called, select query is fired immediately. The returned object is not proxy but of actual class. e.g.

    Software sw = ( Software )session.get(Software.class, 12);
    

    Here sw is of type Software itself. If row exists then all mapped properties are populated with the values in DB. If row does not exist then sw will be null.

    sw  Software  (id=17)   
    id  Integer  (id=20)    
    prop1   "prodjlt1" (id=23)  
    softwareprop    "softwrjlt1" (id=27)    
    

    So as always said, use load only if you are sure that record does exist in DB. In that case it is harmless to work with the proxy and will be helpful delaying DB query till the mapped property is actually needed.

提交回复
热议问题