Is it possible to detach Hibernate entity, so that changes to object are not automatically saved to database?

Solution 1:

You can detach an entity by calling Session.evict().

Other options are create a defensive copy of your entity before translation of values, or use a DTO instead of the entity in that code. I think these options are more elegant since they don't couple conversion to JSON and persistence layer.

Solution 2:

I am also converting hibernate entities to JSON.

The bad thing when you close the session you cannot lazy load objects. For this reason you can use

hSession.setDefaultReadOnly(true);

and close the session after when you're done with the JSON.

Solution 3:

You can also avoid that your entities are attached to the Hibernate Session by using a StatelessSession:

StatelessSession session = sessionFactory.openStatelessSession();

instead of

Session session = sessionFactory.getCurrentSession();

Note that you must take care yourself of closing the StatelessSession, unlike the regular Hibernate Session:

session.close(); // do this after you are done with the session

Another difference compared to the regular Session is that a StatelessSession can not fetch collections. I see it's main purpose for data-fetching-only SQLQuery stuff.

You can read more about the different session types here:

http://www.interviewadda.com/difference-between-getcurrentsession-opensession-and-openstatelesssession/