How do you deep clone a persistent entity in ColdFusion ORM?

徘徊边缘 提交于 2019-12-23 19:11:09

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7592706/how-do-you-deep-clone-a-persistent-entity-in-coldfusion-orm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!