从 JPA/EJB3 持久化上下文中分离实体 [英] Detach an entity from JPA/EJB3 persistence context

查看:22
本文介绍了从 JPA/EJB3 持久化上下文中分离实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分离通过 EntityManager 获取的特定 JPA 实体 Bean 的最简单方法是什么.或者,我是否可以首先让查询返回分离的对象,以便它们基本上充当只读"?

What would be the easiest way to detach a specific JPA Entity Bean that was acquired through an EntityManager. Alternatively, could I have a query return detached objects in the first place so they would essentially act as 'read only'?

我想这样做的原因是因为我想修改 bean 中的数据 - 仅在我的应用程序中使用,但从未将其持久化到数据库中.在我的程序中,我最终必须在 EntityManager 上调用 flush(),这会将所有从附加实体到底层数据库的更改持久化,但我想排除特定对象.

The reason why I want to do this is becuase I want to modify the data within the bean - with in my application only, but not ever have it persisted to the database. In my program, I eventually have to call flush() on the EntityManager, which would persist all changes from attached entities to the underyling database, but I want to exclude specific objects.

推荐答案

遗憾的是,在当前的 JPA 实现 AFAIR 中,无法将一个对象与实体管理器断开连接.

Unfortunately, there's no way to disconnect one object from the entity manager in the current JPA implementation, AFAIR.

EntityManager.clear() 将断开所有 JPA 对象的连接,因此这可能不是所有情况下的合适解决方案,如果您确实计划保持连接的其他对象.

EntityManager.clear() will disconnect all the JPA objects, so that might not be an appropriate solution in all the cases, if you have other objects you do plan to keep connected.

因此,最好的办法是克隆对象并将克隆传递给更改对象的代码.由于默认克隆机制以适当的方式处理原始和不可变对象字段,因此您无需编写大量管道代码(除了深度克隆您可能拥有的任何聚合结构).

So your best bet would be to clone the objects and pass the clones to the code that changes the objects. Since primitive and immutable object fields are taken care of by the default cloning mechanism in a proper way, you won't have to write a lot of plumbing code (apart from deep cloning any aggregated structures you might have).

这篇关于从 JPA/EJB3 持久化上下文中分离实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆