title: Spring JPA - persisting nested objects
body: <p>I have a simple JPA repository that looks like this:</p>
  
  <pre><code>public interface UserRepository extends JpaRepository&lt;User, String&gt;
  {
      User findByName(String name);
  }
  </code></pre>
  
  <p>And two classes that have a OneToOne mapping, like this:</p>
  
  <pre><code>@Entity
  public class User
  {
      @Id
      @GeneratedValue(generator = "uuid")
      @GenericGenerator(name = "uuid", strategy = "uuid2")
      protected String uuid;
  
      @Column(nullable = false, unique = true)
      private String name;
  
      @Column(nullable = false)
      private String email;
  
      @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
      private PlayerCharacter playerCharacter;
  
      //...
  }
  </code></pre>
  
  <p>.</p>
  
  <pre><code>@Entity
  public class PlayerCharacter
  {
      @Id
      @GeneratedValue(generator = "uuid")
      @GenericGenerator(name = "uuid", strategy = "uuid2")
      protected String uuid;
  
      @OneToOne(optional = true)
      private User user;
  
      @Column(nullable = false)
      private String characterName;
  
      //...
  }
  </code></pre>
  
  <p>Now, I know that I can easily edit and persist a User instance like this:</p>
  
  <pre><code>User user = userRepository.findByName("Alice");
  PlayerCharacter character = user.getPlayerCharacter();
  character.setCharacterName("ConanTheBarbarian");
  userRepository.save(user);
  </code></pre>
  
  <p>But how would I persist a <code>PlayerCharacter</code> instance from within a context where I don't have a pointer back to the <code>User</code> instance, f.i.:</p>
  
  <pre><code>public void changePlayerCharacterName(PlayerCharacter character, String name){
      character.setCharacterName(name);
      // How to correctly persist the 'character' instance here?
  }
  </code></pre>
  
  <p>Can I just call <code>userRepository.save(character);</code>?</p>
  
  <p>Do I need to autowire another repository (<code>PlayerCharacterRepository</code>) and call .save() on it?</p>