Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 697
newbie Avatar asked Apr 27 '11 07:04

newbie


People also ask

How do you detach an object in hibernate?

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.

How do you make a detached object persistence in hibernate?

Detached instances may be made persistent by calling update() , saveOrUpdate() , lock() or replicate() . The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge() .

Which method is used to persist the change of state of a detached entity?

Persist the transient or detached entity using persist(), save(), update() or saveOrUpdate() methods.

What does EntityManager detach do?

detach. Remove the given entity from the persistence context, causing a managed entity to become detached. Unflushed changes made to the entity if any (including removal of the entity), will not be synchronized to the database. Entities which previously referenced the detached entity will continue to reference it.


2 Answers

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.

like image 93
axtavt Avatar answered Oct 07 '22 17:10

axtavt


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.

like image 26
elkarel Avatar answered Oct 07 '22 17:10

elkarel