Difference Between Hibernate get() and load() Methods ?
What is the difference between hibernate get() and load() methods ? this is one of the famous hibernate interview questions, most of us will use hibernate get and load methods irrespective of knowing their exact behavior 🙂 will you accept that ? of course even myself too in the initial stages 🙂 Today i will try to clear that confusion.
Few Points About Hibernate get() & load()
- Both are from Session interface, and we will call them as session.get() & session.load()
- Both will be use for retrieving the object (a row) from the database
Then what’s the difference them ? lets start with load() and then get() method.
Consider a Student class having 3 properties stdId, stdName, stdCountry
- When you call session.load() method, it will always return a “proxy” object, whats the meaning of proxy object ?
- Proxy means, hibernate will prepare some fake object with given identifier value in the memory without hitting the database, for example if we call session.load(Student.class,new Integer(107)); > hibernate will create one fake Student object [row] in the memory with id 107, but remaining properties of Student class will not even be initialized, observe this graphical representation…
- It will hit the database only when we try to retrieve the other properties of Student object i mean stdName, stdCountry. If we call s2.getStdName() then hibernate will hit the database and search the row with student id 107 and retrieve the values, if object [row] not found in the database it will throws ObjectNotFoundException.,
Let me explain each point by taking an example
Example of session.load()
System.out.println("Student is calling with load()"); s2 =(Student) session.load(Student.class,new Integer(107)); System.out.println("Student called with load()"); System.out.println("Printing Student Name___"+s2.getStdtId()); System.out.println("Printing Student Name___"+s2.getStdName());
In index.jsp > line number 4, i have called s2.getStdtId() and hibernate simply printed 107 [at Output > line number 3] without creating any database query why ? because as i have explained hibernate will prepare some fake object with given identifier value in the memory without hitting the database. So when we call load() method (at index.jsp > line number 2 ) with 107 value, hibernate will create a fake object with 107 as identifier value, i mean temporarily it will consider the student id as 107. If you observe the output, hibernate was generated the database query (at Output > line number 4 ) when we called s2.getStdName(); ( index.jsp > line number 5 ).
That’s it, so finally we came to know that session.load() will hit the database only when we start retrieving the object (row) values.
- When you call session.get() method, it will hit the database immediately and returns the original object
- If the row is not available in the database, it returns null
Example of session.get()
System.out.println("Student is calling with get()"); s1 = (Student) session.get(Student.class,new Integer(107)); System.out.println("Student called with get()"); System.out.println("Printing Student Name___"+s1.getStdtId()); System.out.println("Printing Student Name___"+s1.getStdName());
- Nothing to explain here 🙂 as i told, when we call session.get() method hibernate will hit the database and returns the original object [ row ], that’s the reason it was generated a query [ check line number 2 in the output screen]
Hmm…, so which is the best method to use, hibernate load() or get() ? its completely your choice 😉
You Might Also Like
::. About the Author .::
Hi Sivateja Kandula,
Really simple explanation and easy to relate. Thank you very much.
Very good explantion…
Best explanation ever…
Really very good explanation. Keep growing 🙂
Article is very very good.
sorry to say in this way: I know the difference as per my text book but in real time in which scenario we have to use load/get till not getting and not assuming also. if you give a simple example , that can be remembered more easily.
If u are not sure that data which is you are searching for is present in dB then u go for load() else get()
keep the same momentum
first of all i thank you very much. your explanations are very nice. it’s easy to understand. My doubt is, get() returns nullpointerexception if the data is not there in the database. you told it returns null. i’m totally confused, can you give a clarification?
Nagarajan: get methode return 'NULL' value when we call Student st=session.get(); if no row exist in the database.
after the if we call st.getId() here it will throw Null Poointer Exception
s1 = (Student) session.get(Student.class,new Integer(107)); // here if s1 value is null. So if you will call any thing with null object obviously it will throw null pointer exception
Can we conclude, that load() is used for lazy loading and get() is used for early loading?
Indeed awesome explanation 🙂
If possible can u please provide JSF tutorial also.
totally disagree load() may hit the database if lazy=false i.e in eagar loading so it not always return proxy object
Really very good explanation.if u try to upload some this type of explanation in other tutorial like Core java,its very helpfull to all .
Its really amazing to understand. I am big fan of you and your posts, I my self improved a lot in java following your blog. Keep it up 🙂
Thank you, sir for this awesome explanation
Your explanation too gud.. keep up the gud work !!!
This hibernate tutorial is very good, I had few queries/doubts before reading this tutorial, but now i am very clear. Thanks a lottttt.
Nice Explanation in easy to understand way.. Colorful text makes it pretty clear in terms of readability.
Each and every word makes sense. Nice explanation this would help to others very much. Easily understandable…… I think all get benefited by u….
Very Good Explanation really helpful.
Very good explanation..Thanks
Really its a great explanation.
There is more to this ( than being an interview question )
As per Hibernate in action book :
The load() method is older; get() was added to Hibernate’s API due to user
request. The difference is trivial:
If load() can’t find the object in the cache or database, an exception is
thrown. The load() method never returns null. The get() method returns
null if the object can’t be found.
Always use get()
Very good and lucid explanation, the very best i have read until now, keep up the good work, all the best!!
According to my perception, your explanation is very easy to understand not only me everybody can understand, i hope
Very nice explained
Thanks buddy !!! If u know pls tell us how merge method works in hibernate.
Good explanation…just want to add on load() method….
Session.load() will use (lazy / eager) loading depends on implementation of persistent class – Final / Non Final.
1. If persistent class is non final then hibernate build proxy of class in cache and use further lazy loading to get others class properties by hitting db.
2. If class is final then hibernate cannot build proxy of class and use eager loading by hitting database.
Good explanation thanks……
Thanks for the elaborated explanation
thanks alot Sivateja Kandula for your well designed material for beginners.learnt alot !!!!
Thanks for explained nice example.
Thanks a lot Sir, this is very clear explanation. Everytime when I tried to understand the difference between load() and get(), I never understood what the proxy is. But you have explained it very well.
Really Good to understand .Thanks
really very good explaination.
Thanks very much for ur explanation ….
simple and sweet.. 🙂 nice explanation
its nice explanation…..i understood clearly…..but my doubt is…why
two method…what is the best…why load returns…proxy…when to use what..
nice explanation sir
Very nice explanation..Thank you very much!!
Can you please share difference between lazy loading and eager loading with example and well explanation?
Very Good Explanation,,, Thanks
Really very good explanation….
It really very good explaination. its really become simple to understand. 🙂
thank you Sivateja, Simple but best explanation ….
very nice explanation
Very good explanation and easier to understand. i didn’t get this much clarity from other popular sites..Thanks
Very good tutorial.Thanks
Very good explanation..
hi sir nice website but i need as spring to hibernate integration examples
and provide some real time examples based on hibernate
thank u sir
I have hands on hibernate earlier but after reading your java4s tutorial i got better idea. Good Job keep it up:)
Nicely explained the difference between get() and load() method.Thanks a lot for sharing such useful information.
Here,I would like to add one more point regarding when we can go for get() and load() method.If you agree upon it,please go ahead and implement in your application,else ignore it.
load() – since, it returns a proxy object of requested entity,we can use it for lazy initialization purpose,where we need only a reference of an object and no other its properties.It actually saves DB hits.
one precaution we have to take is that we should use this method only when the data is present in the DB ,else it throws the exception.
get() – we should go with this method when we want to make sure the required object i.e. data is present in the DB.
Thanks for your inputs Swapnil. 🙂
doesn't make any sense, in both cases data should be there in the database. How does It makes any usages difference.
Explain different method of loading ? It is question of insurance exam final years. Please help
Thank u. very nice explanation. grt job
Very good explaination:) Way to go !!!
Thank’s Nice explaing
Very clear explanation
you are awesome bro. i never see such kind of explanation which so much clarity.Thanku so much
Really good explanation,after reding this not only me but no any one having problem in get and load method
Thank you very much for these good tutorials.
I was scared of Hibernate before but now I feel its easy. 🙂
Thank you Java4s Team.
Thank u For this tutorial, and Very Good explain.
really its a very very good explanation….
simply superb explanation keep going
Only one word "awesome"
really explained very simply and can be understand easily.
please explain more about load() and get() for annotation..
really explained good and never seen this type of explaination
Great Tutorial.Awesome 🙂
Very nicely Explained, Thanks sir.
Could you please explain about locking in hibernate.
how to create proxy object in session.load().method,can u explain the internal proces?
Hello Sir,Your Explanation is super with graphical representation and with simple examples,Thank you Sir.
Super Explanation,Thank you much
I am getting an error called " org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] ".
Clear Explanation , Easy to understand thanks for sharing.
Finally, i have completed this tutorial.
Your tutorial is very easy to follow it.
That is an awesome explanation. Thanks Man!! 🙂
its awesome explanation…..everyone can understand very easily…..thnx
Excellent and Awesome explanation.
You said —- so which is the best method to use, hibernate load() or get() ? its completely your choice.
I am not satisfied.. I think load() method is used whenever you are sure about the existence of an object otherwise get() method is used cause when you call load()method with 101 id which is not exist in db then hibernate returns you as proxy object with 101 id i.e not right.so it choose whenever you are sure about exist of data.
How can you predict whether the data is available in the DB?
I cant predict about the existence of data but i want to say that there is no means of load methods because if there is no data in db it return proxy id 101.
So it is always choose to get methods right.
I agree, but if you choose get, lets say object is not available in the database, it will return NULL and further if we do any operations on NULL it will throw NullPointerException, then both Load and Get doing the same!
Excellent explanation…I was searching better answer and here I could see moreover no question to ask after reading this topic…keep it up…
Came here for a better though. I found basic one. Not bad.
Really its a great explanation.
Awesome. Now I got it. always wondering when load exception is thrown without checking identifier. how it created proxy object etc. U rock Man!!
Really its a great explanation.
I'm waiting for other interesting topics
Yes, Really it's great explanation
imp interview question
Load():- Lazy loading
Your way of explanation is awesome. Very easy and clear to understand the concept and especially with this kind of explanation its very easy to remember the things in memory.
hai i am using hibernate 4.3.5 jar,
it will always return a “proxy” object whit out hit db;
Session session = factory.openSession();
Product product = (Product) session.load(Product.class, 105);
Hibernate: select product0_.p_id as p_id1_0_0_, product0_.price as price2_0_0_, product0_.p_name as p_name3_0_0_ from product product0_ where product0_.p_id=?
i am print id .hit db;
Very simple and clear explanation. Saved so much of time.
Hi Sivateja, Usually, I am not commanding, but this website gives extraordinary explanation hats off man.
Very Good Explanation Thank you very much
Good Explaination thanks