如何在 ColdFusion ORM 中深度克隆持久实体?

发布于 2024-12-07 06:44:29 字数 830 浏览 6 评论 0原文

我有一个用作模板的持久实体:

Company
    Locations
        Departments
            Employees

换句话说,公司包含许多位置,其中包含许多部门,其中包含许多员工。我将一家 Company 设置为模板,在创建新公司时应复制该模板。但是,该模板在数据库中是持久的。我尝试使用以下代码来深度克隆它:

var template = EntityLoadByPK("Company", 13);
var company =  Duplicate(template);
EntitySave(company);

但我收到一条错误,指出该实体未附加到会话。因此,我尝试在保存之前将 0 分配给所有 ID:

company.setId(0);
for (location in company.getLocations())
{
    location.setId(0);
    // more nested for loops
}

但我收到了类似的错误。最后,我尝试直接进行属性的 1:1 复制:

var newCompany = EntityNew("Company");
newCompany.setName(company.getName());
newCompany.setCEO(company.getCEO());
// etc...

但是对象图越深入,这就会变得越来越麻烦。是否有更简单的方法来深度克隆持久实体,以便获得一个全新的瞬态实体,包括其所有子集合?

I have a persistent entity that I'm using as a template:

Company
    Locations
        Departments
            Employees

In other words, a Company contains many Locations, which contains many Departments, which contains many Employees. I have one Company set up as a template that should be copied when a new company is created. However, this template is persistent in the database. I tried using the following code to deep clone it:

var template = EntityLoadByPK("Company", 13);
var company =  Duplicate(template);
EntitySave(company);

But I receive an error says that the entity is not attached to the session. So then I tried to assign 0 to all the IDs before saving:

company.setId(0);
for (location in company.getLocations())
{
    location.setId(0);
    // more nested for loops
}

But I receive a similar error. Finally, I tried to do a direct 1:1 copy of the properties:

var newCompany = EntityNew("Company");
newCompany.setName(company.getName());
newCompany.setCEO(company.getCEO());
// etc...

But this gets more and more cumbersome the deeper the object graph goes. Is there an easier way of deep cloning a persistent entity so that you get a brand new transient entity, including all of its child collections?

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

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

发布评论

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

评论(2

嘿咻 2024-12-14 06:44:29

上次我遇到同样的情况,我只是在根CFC中编写了一个类似克隆的方法。顺便说一句,不能称其为“克隆”,因为我相信它是保留的。

last time I encountered the same situation, I just wrote a clone-like method in the root CFC. Cannot call it clone btw, 'cause it's reserved I believe.

邮友 2024-12-14 06:44:29

您是否尝试过使用 EntityMerge?您应该能够复制 ORM 对象,将 ID 设为 NULL,然后将其合并回会话中。

Have you tried using EntityMerge? You should be able to duplicate an ORM object, NULL out the IDs, and then Merge it back into the session.

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