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?
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.
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() .
Persist the transient or detached entity using persist(), save(), update() or saveOrUpdate() methods.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With