When do I see updates on hibernate entities?

Viewed 51

Let's say I'm using spring and hibernate and I do something like the following in one of my transactional service methods. What would be the expected outcomes of the prints and more importantly why?

// user1 perviously has some other name then x
User userInstance = userDAO.findById(1);
userInstance.setName("x");
System.out.println(userDAO.findById(1).getName());

userDAO.save(userInstance);
System.out.println(userDAO.findById(1).getName());

Would I always expect to see the changes that I made to the user entity I queried and why? How exactly does this interact with the hibernate proxy and the first level cache?

Thanks for any insights!

2 Answers

Within the same session, Hibernate will use the first level cache to ensure that the same entity (identified by the same primary key) is always represented by the same object instance. This means that until you close the session, whether you interact with the referenced entity userInstance or you do it trough Hibernate with userDAO.findById(1) you will always be referring to the exact same object instance.

So to answer your question, the printed result would be: x x

I assume that line 2 should have used userInstance instead of userInstance1. I think you will see an update flushed to the database when line 3 (below) is executed:

System.out.println(userDAO.findById(1).getName());

The reason is that you have an unsaved but updated the version in memory so it is considered "dirty". When you re-read that same object (based on the ID), hibernate will flush the updated object first to the database before re-reading it.

Related