Search code examples
javahibernatepersistence

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


I have Hibernate entity that I have to convert to JSON, and I have to translate some values in entity, but when I translate values, these values are instantly saved to database, but I don't want to save these changes to database. Is there any workaround for this problem?


Solution

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

    In case of JPA, you can use: EntityManager.detach(object)

    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.