This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Session session=HibernateUtil.beginTransaction(); User user1 = new User(); user1.setPassword("aaaaaa"); Long id = (Long)session.save(user1); session.evict(user1); User user2 = (User)session.get(User.class, id); user1.setVerified(true); session.saveOrUpdate(user1); HibernateUtil.commitTransaction();
Here i've not committed "user1" instance. I've just cached "user1" instance using save method & as I know if we don't commit the transaction that instance would not have been saved to Database right. By that rule, "user1" would not have been saved to Database & when I try to look for that instance using get method
User user2 = (User)session.get(User.class, id);
it should throw some exception right. please throw some light on this?
Hibernate does not synchronize its session with the database only while committing a transaction. It can do it when it "senses" it is necessary to keep a certain coherency.
In your piece of code hibernate actually saves your user1 to give you the id. After the evict() user1 is a detached object, therefore no more in the hibernate session. So when you get user2, it is an object with the same idea than user1 but located in the session. There is no conflict.