是否可以分离 Hibernate 实体,以便对象的更改不会自动保存到数据库?
我有一个必须转换为 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.