如何从@Transactional方法中驱逐一个实体,以防止其持久化?

huangapple go评论91阅读模式
英文:

How to evict an entity from a @Transactional method to prevent its persistence?

问题

我有一个事务,需要更新一个特定的实体A,问题是在同一个事务中,为了获取更新实体A所需的数据,需要访问另一个与数据库相关联的实体B。

这本来没问题,但问题是它不仅仅是获取实体B,还会更新实体B,所以在事务结束时,它会同时更新实体A和实体B,而实际上只应该更新实体A。

这段代码非常旧了,而且实体B非常庞大,无法创建一个POJO或类似的东西来避免直接编辑实体B。

我进行了一些研究,发现了session.evict(instanceOfEntityB),但问题是它似乎不起作用,因为它仍然会更新这个实体(通过检查数据库中的版本,它发生了变化...)。所以我想知道是否有其他方法可以阻止实体B的持久化。

英文:

I have a transaction that has to update a specific entity A, the problem is that in that same transaction, in order to get the data needed to update this entity A, it takes another entity linked to the database (Entity B).

This would be ok, but the problem is that it does not just take it, it updates entity B, so at the end of the transaction, it updates Entity A and Entity B when it should only update Entity A.

This code is very old, and the Entity B is huge in order to create a POJO or something like that to avoid editing the entity B directly.

I've been researching and I found session.evict(instanceOfEntityB) but the problem is that this does not seem to be working, as it is updating this entity (checking the version in the database, it changes...). So I wanted to know if there is another way to prevent Entity B from persisting.

答案1

得分: 1

你可以使用entityManager.detach(yourEntity)方法。

该方法将给定的实体从持久化上下文中移除,使得被管理的实体变为游离状态。如果有对实体进行的未刷新的更改(包括删除实体),这些更改将不会同步到数据库。之前引用该游离实体的实体将继续引用它。

英文:

you can use entityManager.detach(yourEntity)

> 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.

huangapple
  • 本文由 发表于 2023年8月8日 21:38:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定