如何在多个数据库(分布式系统)中持久保存同一个JPA实体?

发布于 2024-07-22 01:21:32 字数 237 浏览 9 评论 0原文

(如何)是否可以将 JPA 实体持久保存在多个服务器的数据库中,而无需将所有内容复制到 DTO?

我们有一个分布式系统。 某些应用程序确实具有用于缓存目的的数据库。 JPA 提供程序抛出一个异常,抱怨它无法持久保存分离的对象。

但我想保留实体的 ID,只需将其保留在这个附加数据库中即可。

(JPA 1.2、EJB 3.0、Glassfish v2.1、Toplink Essentials)

(How) is it possible to persist a JPA Entity at the databases of multiple servers without copying everything to DTOs?

We have a distributed system. Some applications do have DBs for caching purposes. The JPA Provider throws an Exception in which it complains that it cannot persist a detached object.

But I would like to preserve the ID of the entity with just persisting it in this additional DB.

(JPA 1.2, EJB 3.0, Glassfish v2.1, Toplink Essentials)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光的暖冬 2024-07-29 01:21:33

不要 em.persist(obj),只需 em.merge(obj)。 合并适用于附加和分离的对象。

如果您从一个分离的对象开始,我会将对象与相应的 EntityManager 合并。 如果您试图在对象之间保持身份密钥相同,我会从合并的第一个对象中提取密钥,并在将来使用它。

您可能(我不知道)不想做的就是尝试将一个 EM 管理的对象与另一个 EM 管理的对象合并。 你可以测试一下它是否有效,我只是不知道如果你尝试会发生什么。

所以。

YourEntity unattachedEntity = ... // your original entity object.

YourEntity managedEntity = em1.merge(unattachedEntity);

// managedEntity now has the primary key assigned by the DB
unattacheEntity.setPrimaryKey(managedEntity.getPrimaryKey());

em2.merge(unattachedEntity);
em3.merge(unattachedEntity);

像这样的东西应该可以正常工作。

Don't em.persist(obj), just em.merge(obj). Merge works with both attached and detached objects.

If you are starting with a detached object, I would merge the object with the respective EntityManagers. If you're trying to keep the identity key the same across the objects, I would pull the key from the first object merged, and use it in the future.

What you probably (I don't know) don't want to do is try and merge an object that is managed by one EM with another EM. You can test this to see if it works, I just don't know what will happen if you try.

So.

YourEntity unattachedEntity = ... // your original entity object.

YourEntity managedEntity = em1.merge(unattachedEntity);

// managedEntity now has the primary key assigned by the DB
unattacheEntity.setPrimaryKey(managedEntity.getPrimaryKey());

em2.merge(unattachedEntity);
em3.merge(unattachedEntity);

Something like that should work ok.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文