Java – Refresh object in Session from Database Hibernate

hibernatejava

Hibernate, as I know updates the Database once the attached Objects in the session's value changes. Is there a way to obtain a fresh copy from the database and reattach the fresh copy discarding the changed object?

Below is an object I obtained from Querying the Database using Hibernate.

Rtpmast rtpmast = (Rtpmast) iterator.next();

Once executed the below code

rtp.setRptval1(promotionMethod.getType());

Hibernate registers that the the object has changed. And when I commit a transaction later on or query the Database the Session is flushed?

What I want is to temporally update the Rtpmast object and discard the changed object later.

Best Answer

Hibernate, as I know updates the Database once the attached Objects in the session's value changes.

Actually,Hibernate updates the database only after invoking session.save(...), session.delete(...) etc. methods. If you're in a transaction you'd also have to commit changes.

What you want is either use evict() and re-query the object, as you've mentioned, or detach the instance you're working on, which means you need to close() the Session (there are other, less trivial, ways to do so as mentioned here).