title: How to get a copy of child entity and save it to another parent using DataNucleus and JDO API?
body: <p>I have a <strong>bidirectional 1 to many relation between SelfEmployed and IncomeExpense</strong> classes. Suppose I have <strong>two different persistent instances of SelfEmployed</strong>. I need to <strong>copy of some SelfExpense object from one parent and add them to another</strong>. </p>
  
  <p>To copy object I just use default constructor to create instance, and then assign only three primitive values, and sets <code>selfEmployed=null</code> instance and <code>id=null</code>.</p>
  
  <p>BUT, when I do the following <code>secondSelfEmployed.getIncomeExpenses().add(incomeExpenseCopy);</code>
  Somehow it finds the origin instance of incomeExpense, and sets the rest fields like <code>id</code> and <code>selfEmployed</code>. Thus, when the transaction commits it <code>throws the exception</code>, that I try to add incomeExpense, that already has its parent object selfEmployed</p>
  
  <blockquote>
    <p>org.datanucleus.exceptions.NucleusUserException: Management of relations : Object "SelfEmployed@6d651cc" has a bidirectional field "incomeExpenses" and the object"IncomeExpense@60942b95" was added to this field, but this field has had its owner set to "SelfEmployed@1fb974bc"!</p>
  </blockquote>
  
  <pre><code>import java.util.HashSet;
  import java.util.Set;
  
  public class SelfEmployed {
  
      protected Set&lt;IncomeExpense&gt; incomeExpenses = new HashSet&lt;IncomeExpense&gt;();
      // some primitive fields
  
      public Set&lt;IncomeExpense&gt; getIncomeExpenses(){
          return incomeExpenses;
      }
      // standard getters and setters
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>    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;
          }
  }
  </code></pre>
  
  <p>The following logic is performed within transaction.
  The problem is here</p>
  
  <pre><code>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
  }
  </code></pre>