title: Persist OneToOne relation with SpringData JPA
body: <p>I have the next two entities with a OneToOne relation between them:</p>
  
  <pre><code>@Entity
  @Table(name = "tasks")
  public class Task {
      @OneToOne(mappedBy = "task", cascade = CascadeType.PERSIST)
      private Tracker tracker;
  
      /* More code */
  }
  
  @Entity
  @Table(name = "trackers")
  public class Tracker {
      @OneToOne
      @JoinColumn(name = "trk_task", unique = true)
      private Task task;
  
      /* More code */
  }
  </code></pre>
  
  <p>I'm trying to run this code:</p>
  
  <pre><code>Task task = taskService.findDispatchableTask();
  if (task != null) {
      Tracker tracker = trackerService.findIdleTracker();
      if (tracker != null) {
          task.setTracker(tracker);
          task.setStatus(TaskStatus.DISPATCHED);
          taskService.save(task);
      }
  }
  </code></pre>
  
  <p>But I get this error:</p>
  
  <pre><code>ERROR org.hibernate.AssertionFailure  - an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session) 
  org.hibernate.AssertionFailure: non-transient entity has a null id
  </code></pre>
  
  <p>I can "solve" it changing my code to:</p>
  
  <pre><code>Task task = taskService.findDispatchableTask();
  if (task != null) {
      Tracker tracker = trackerService.findIdleTracker();
      if (tracker != null) {
          tracker.setTask(task);
          trackerService.save(tracker);
          task.setTracker(tracker);
          task.setStatus(TaskStatus.DISPATCHED);
          taskService.save(task);
      }
  }
  </code></pre>
  
  <p>My question is, Which is the proper way to persist a OneToOne relation? In my code, Why do I have save both parts of the relation to make it work?</p>