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

查看:107
本文介绍了从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(),它会将所有更改从附加实体持久保存到underyling数据库,但我想排除特定对象。

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天全站免登陆