休眠更新我的实体

休眠更新我的实体

本文介绍了休眠更新我的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了2个实体.现在,当我在后端检索我的实体时,我会验证一些事情,但是当我的后端将那些实体返回到我的前端时,休眠模式会尝试自动更新数据库.

I have created 2 entities.Now when I retrieve my entities in my backend I verify some things, but when my backend return those entities to my frontend the hibernate try to update automatically the db.

我实际上没有在后端代码中运行任何更新(我认为是因为我在执行逻辑时更改了实体中的某些数据,并删除了一些应返回至前端的属性).

I don't actually run any update in my backend code (I think it`s because I change some data in my entity while i do my logic and remove some properties that I should return to my frontend).

在显式运行.save或.update之前,如何告诉休眠状态不更新任何内容?

How can I tell to hibernate to not update anything until I run .save or .update explicitly?

推荐答案

您已经在注释中找到了内容,但让我将其汇总为一个答案:

You already got the pieces in the comments, but let me put it together in an answer:

这种解释是正确的.

如果您通过JPA加载实体,则该实体将附加到会话中,并且在关闭会话/提交事务后,对它的所有更改都会被跟踪并写入数据库.

If you load an entity via JPA it is attached to a session and every change to it gets tracked and written to the database once you close the session/ commit the transaction.

为了避免您需要从会话中删除实体.您可以通过以下任何一种方式进行

In order to avoid that you need to remove the entity from the session. You can do that by either

在执行操作之前关闭EntityManager/事务.这基本上意味着您要对最外部方法之外的实体进行更改,并用@Transactional

closing the EntityManager / transaction before doing the manipulation. This basically means doing your changes to the entity outside the outer most method annotated with @Transactional

请注意,在两种情况下,延迟加载都不再起作用,因此必须确保在分离实体之前已加载所需的所有内容.

Note that in both cases lazy loading won't work anymore so you'll have to make sure you loaded everything you needed before detaching the entity.

这篇关于休眠更新我的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:49