简体   繁体   中英

JPA detached object and primary key

Thanks in advance for all your help.

I have an detached object with child objects. I have to insert or delete the child objects in order. So I am changing the primary key values of the child. Then I remove every child from the database. Then recreate all the child objects but eclipselink is complaining about the primary key already exist can not update database Here is my code

Quotation q = ejbFacade.find(selected.getQuotationPK());
    for (QTitle qt : q.getQTitleList()) {
        for (QActivity qa : qt.getQActivityList()) {
            for (QCategorywork qc : qa.getQCategoryworkList()) {
                for (QManual qm : qc.getQManualList()) {
                    qmFacade.remove(qm);
                }
                for (QProduct qp : qc.getQProductList()) {
                    qpFacade.remove(qp);
                }
                qcFacade.remove(qc);
            }
            qaFacade.remove(qa);
        }
        qtFacade.remove(qt);
    }
    for (QTitle qt : selected.getQTitleList()) {
        qtFacade.create(qt);
        for (QActivity qa : qt.getQActivityList()) {
            qaFacade.create(qa);
            for (QCategorywork qc : qa.getQCategoryworkList()) {
                qcFacade.create(qc);
                for (QManual qm : qc.getQManualList()) {
                    qmFacade.create(qm);
                }
                for (QProduct qp : qc.getQProductList()) {
                    qpFacade.create(qp);
                }
            }
        }
    }
    ejbFacade.merge(selected);
    ejbFacade.refresh(selected);

The object selected is detached and all the children has cascadetype.all set. May be there is some other efficient way of doing the above. Any advice!!

you say:

I remove every child from the database.

and you also say:

Then recreate all the child objects

Please try to execute those two operations in their own transaction boundary. You will surely see the

complaining about the primary key already exist

has gone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM