Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between get() and load() methods in Hibernate

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 1.20k
    Comment on it

    What is the difference between get() and load(): The most important question for the interview's perspectives that what is the difference between get and load methods in Hibernate? Developers use both the functions when coding but most of them use them without knowing the pros and cons of these methods.

    In this article we will try to make you understand the similarities and difference between hibernate load and get methods.


    Similarities between load() and get() methods :

    1. The load() and get() both methods used to retrieve object (a row) from database.
    2. Syntax wise both load() and get() methods are same.
    3. load() method is older whereas get() is new, but both belongs to Hibernate API.
    4. load() and get() both methods belongs to Session interface.

    Difference between load() and get() methods : Suppose we have a Student student object having two fields id and name and it's getters and setters methods.

    1. When we call the sesssion.load() method it will create the proxy or dummy object of Student class in the memory, for example if we call session.load(101) then it will create a dummy object in the memory contains the id value 101 and value of name fields as null, but when we call the getName() method then it will hit the db and retrieve the row of the object id of 101. Whereas other method session.get() will direct hit the database to retrieve the value of the all fields of student object, for example session.get(101) will hit the database and fetch a record for identifier 101.

    2. If session.load() can't find the object in the cache of database, it will throw the ObjectNotFoundException exception, but sesssion.get() not.

    3. If session.get() can't find the object in the cache or database it will return null, but session.load() throws the ObjectNotFoundException exception.


    Conclusion:

    1. The get() method hits the database and fetch the object as soon as we called the method but in load() method it fetched the record when needed, it supports the lazy loading. So load() is better then the get().
    2. We only needs to use load() when we are sure that data is present in the database otherwise it will throw the exception.
    3. We should use get() method when we want to check the data is present in db or not.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: