Thursday, January 9, 2014

Difference Between Get and Load in Hibernate

1)
package hibapp;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Rishitha
 */
public class GetAndLoad {
   
   
    public static void main(String args[]){
       
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        Session ses = sf.openSession();
       
        //In Hibernate you can load object with
        //1)Load or 2)Get
       
       
       
        //Let Us First See Load Method...
        //and try to find an existing record
       
        PostTo st = (PostTo)ses.load(PostTo.class, new Long(1));
       
        System.out.println("Select query won't be fired by this time by the above"
                + " load method call");
         
        //At this step no select query will be executed in case
        //of Load,Hibernate creates a dummy object and just load
        //the primary key value.In this case it create a proxy
        //object which looks similar to PostTo and populates
        //the id with 1
       
        //When you call get on any non primary key property
        //Select query gets fired
        System.out.println("Now Select Query Fires because you have accessed "+
        "non primary key propert i.e getConent");
        String content = st.getContent();
       
        System.out.println("Post Content "+content);
       
       
        //Now we will try to load unexisting record
         PostTo unexPost = (PostTo)ses.load(PostTo.class, new Long(100));
         System.out.println("You might expect that above line throws exception "+
             "But as I said.. by that time... with out firing any select query "+
              "hibernate just returns proxy object with primary key set ");
        System.out.println("\n");
         System.out.println("After accessing getContent in the below you get the exception "+
         "because hibernate fires the select query now ");
        try{
           unexPost.getContent();
        }catch(Exception e ){
            System.out.println("Load throws exception when we try to load "
                    + "non existing object ");
        }
     
       
            
        //Now we will see Get
        //Get immediately fires the select query
        //If it doesn't find.. the record it will give null....
        ses=sf.openSession();
        System.out.println("\n");
        System.out.println("With Get hibernate fires select query  immediately unlike "
                + "Load which fires select only when... non primary key property"
                + "is accessed.Also you have to remember another important point get"
                + "first checks if the object you are trying to retrieve is in first level cache"
                + "that is session cache.. if that is not available then fires select query\n ");
        PostTo post = (PostTo)ses.get(PostTo.class, new Long(1));
        System.out.println("Conetent from Get "+post.getContent());
       
        System.out.println("\n Now I am trying to get the post 1 again but you observe"
                + " it won't fire select query again because in the above step post 1 is loaded and "
                + " it is already in session cache ");
        post =  (PostTo)ses.get(PostTo.class, new Long(1));
       
       
        System.out.println("\nTrying to get non existing object ");
        post = (PostTo)ses.get(PostTo.class,new Long(100));
        System.out.println("\nGet returns null and it doesn't throw exception like load method ");
       
   
    }
   
  
   
}












2)



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
    <property name="hibernate.connection.username">hr</property>
    <property name="hibernate.connection.password">hr</property>
    <property name="hibernate.hbm2ddl.auto" >update</property>
    <property name="hibernate.show_sql">true</property>
    <mapping class="hibapp.PostTo"/>  
  
  </session-factory>
</hibernate-configuration>





3)
package hibapp;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author Rishitha
 */
@Entity
@Table(name="jlposts")
public class PostTo {
    @Id
    Long postId;
    String submittedBy;
    String content;
   
    public PostTo(){}

    public Long getPostId() {
        return postId;
    }

    public void setPostId(Long postId) {
        this.postId = postId;
    }

    public String getSubmittedBy() {
        return submittedBy;
    }

    public void setSubmittedBy(String submittedBy) {
        this.submittedBy = submittedBy;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
   
   
}


Assumption: Assume Only one record with post id 1 exists
insert into jlposts values(1,'Anil','TestContent');

Output:
---------
Select query won't be fired by this time by the above load method call
Now Select Query Fires because you have accessed non primary key propert i.e getConent
Hibernate: select postto0_.postId as postId0_0_, postto0_.content as content0_0_, postto0_.submittedBy as submitte3_0_0_ from jlposts postto0_ where postto0_.postId=?
Post Content Anil
You might expect that above line throws exception But as I said.. by that time... with out firing any select query hibernate just returns proxy object with primary key set


After accessing getContent in the below you get the exception because hibernate fires the select query now
Hibernate: select postto0_.postId as postId0_0_, postto0_.content as content0_0_, postto0_.submittedBy as submitte3_0_0_ from jlposts postto0_ where postto0_.postId=?
Load throws exception when we try to load non existing object


With Get hibernate fires select query  immediately unlike Load which fires select only when... non primary key propertyis accessed.Also you have to remember another important point hibernatefirst checks if the object you are trying to retrieve is in first level cachethat is session cache.. if that is not available then fires select query

Hibernate: select postto0_.postId as postId0_0_, postto0_.content as content0_0_, postto0_.submittedBy as submitte3_0_0_ from jlposts postto0_ where postto0_.postId=?
Conetent from Get Anil

 Now I am trying to get the post 1 again but you observe it won't fire select query again because in the above step post 1 is loaded and  it is already in session cache

Trying to get non existing object
Hibernate: select postto0_.postId as postId0_0_, postto0_.content as content0_0_, postto0_.submittedBy as submitte3_0_0_ from jlposts postto0_ where postto0_.postId=?

Get returns null and it doesn't throw exception like load method 










No comments:

Post a Comment