views:

63

answers:

2

I have a strange use case of Hibernate where in a call farther up a large stack needs an unmodified copy of an object that is part of a hibernate transaction. however, every time I ask Hibernate for a copy of the object, it's returning the version that's already been modified / is part of the transaction.

Is there a way for me to force Hibernate to return the db copy / uncached version of object in question?

+1  A: 

Open a new Session and get the copy of the object from the new Session.

Justice
in case the session opening/closing is delegated to a framework (like spring), then opening a new session might be cumbersome. And generally, opening and closing a session for this issue is a bit like killing a fly with a bazooka :)
Bozho
Sessions are supposed to be lightweight. If you want a fresh object, open a session and get it. The session factories are heavyweight, and should always be available via some framework API in case there is a need for it (such as this need).
Justice
+1  A: 
Session#refresh(Object object);

Re-read the state of the given instance from the underlying database.

or you can call session.evict(obj) (removes it from the session cache) and load() it afresh.

Note that if you are using EntityManager instead of Session, you won't have the evict() method. You can obtain the Session this way:

Session session = (Session) entityManager.getDelegate();
Bozho