是否可以分离 Hibernate 实体,以便对象的更改不会自动保存到数据库? [英] Is it possible to detach Hibernate entity, so that changes to object are not automatically saved to database?
问题描述
我有一个必须转换为 JSON 的 Hibernate 实体,我必须转换实体中的一些值,但是当我转换值时,这些值会立即保存到数据库中,但我不想将这些更改保存到数据库.这个问题有什么解决方法吗?
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?
推荐答案
您可以通过调用 Session.evict()
.
You can detach an entity by calling Session.evict()
.
其他选项是在转换值之前创建实体的防御副本,或者使用 DTO 代替该代码中的实体.我认为这些选项更优雅,因为它们没有将转换成 JSON 和持久层.
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.
这篇关于是否可以分离 Hibernate 实体,以便对象的更改不会自动保存到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!