aspose file tools*
The moose likes Object Relational Mapping and the fly likes Doubt in an Object instance while using evict() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Doubt in an Object instance while using evict() method" Watch "Doubt in an Object instance while using evict() method" New topic
Author

Doubt in an Object instance while using evict() method

ramya narayanan
Ranch Hand

Joined: Oct 06, 2008
Posts: 338


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?
ramya narayanan
Ranch Hand

Joined: Oct 06, 2008
Posts: 338
Any reply?
ntumba lobo
Ranch Hand

Joined: Oct 21, 2008
Posts: 180
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.


SCJP 5 , SCWCD 5, SCEA 5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in an Object instance while using evict() method