• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object is getting updated without the use of merge

 
Yogesh Gandhi
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI Friends,

I have little bit knowledge of JPA and hibernate.
My knowledge finds it surprising that object is getting saved to the database without the use of merge/update/persist method of hibernate.

I'll explain with the help of code snippet

Here is my main code


I search a user with the username aswin and set its first name and last name.



here is the update User method




And The user row in the database is getting updated. What I am not able to understand is, how is this possible? How is hibernate knowing which object it has to update...

We have not passed the user pojo forward to the hibernate API. How it comes to know which object to update?

User is a POJO with annotations and mapping to the USR table.

Can anyone please help me in this regard?
 
Jana reddyMadam
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. This concept is called dirty checking.

When you get User object from searchUser method , you have not closed the session , so the session is still active.

User user = userManagementServiceImpl.searchUser("aswin");

With the active session , this object is now persistent object which means , when you commit the transaction, Hibernate tries to check with original instance called Dirty changing, if there is any change this will automatically update the data base ;).

This is a cool feature of hibernate, which inside uses the primary level Cache. Read about primary caching and dirty checking - you will understand more.

Regards
Jana


 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic