如何使用DataNucleus和JDO API获取子实体的副本并将其保存到另一个父实体?

时间:2017-03-16 09:16:42

标签: jdo datanucleus

我在SelfEmployed和IncomeExpense 类之间有一个双向1对多关系。假设我有两个不同的SelfEmployed持久化实例。我需要从一个父项复制一些SelfExpense对象并将它们添加到另一个

要复制对象,我只需使用默认构造函数创建实例,然后只分配三个原始值,并设置selfEmployed=null实例和id=null

但是,当我执行以下操作时secondSelfEmployed.getIncomeExpenses().add(incomeExpenseCopy); 它以某种方式找到了incomeExpense的原始实例,并设置了其他字段,如idselfEmployed。因此,当事务提交它throws the exception时,我尝试添加incomeExpense,已经有其父对象selfEmployed

  

org.datanucleus.exceptions.NucleusUserException:关系管理:对象“SelfEmployed @ 6d651cc”具有双向字段“incomeExpenses”,对象“IncomeExpense @ 60942b95”已添加到此字段中,但此字段已设置其所有者到“SelfEmployed @ 1fb974bc”!

import java.util.HashSet;
import java.util.Set;

public class SelfEmployed {

    protected Set<IncomeExpense> incomeExpenses = new HashSet<IncomeExpense>();
    // some primitive fields

    public Set<IncomeExpense> getIncomeExpenses(){
        return incomeExpenses;
    }
    // standard getters and setters
}

    public class IncomeExpense {
        protected int year;
        protected Double annualGrossTurnover;
        protected Double annualExpenses;
        protected SelfEmployed selfEmployed;


        // standard getters and setters 

        public void setSelfEmployed(SelfEmployed selfEmployed) {
            this.selfEmployed = selfEmployed;
        }

        public SelfEmployed getSelfEmployed() {
            return selfEmployed;
        }
}

在事务中执行以下逻辑。 问题出在这里

for (IncomeExpense ie: selfEmployed1.getIncomeExpenses()){
    IncomeExpense copy = new IncomeExpense();
    copy.setYear(ie.getYear());
    copy.setAnnualGrossTurnover(ie.getAnnualGrossTurnover());
    copy.setAnnualExpenses(ie.getAnnualExpenses());

    selfEmployed2.getIncomeExpenses().add(copy);// on this line it sets to copy fields id, and selfEmployed, that was in ie
}

0 个答案:

没有答案