title: Handling relations in POST requests with Spring Data JPA
body: <p>I have the following entities, and a <code>CrudRepository</code> for each:</p>
  
  <pre><code>@Entity
  class Movie {
      @Id Long id;
      @Column String name;
      @ManyToOne Person director;
  }
  
  @Entity
  class Person {
      @Id Long id;
      @Column String name;
  }
  </code></pre>
  
  <p>My controller looks like this:</p>
  
  <pre><code>@RestController
  @RequestMapping("/movies")
  class MovieController {
  
      private MovieRepository movies = ...;
      private PersonRepository people = ...;
  
      @PostMapping
      public Movie create(@RequestBody MovieRequest request) {
          // Get the director
          Person director = people.findById(request.directorId);
  
          // Create the new movie
          Movie movie = new Movie();
          movie.name = request.name;
          movie.director = director;
  
         // Save the new movie
         return movies.save(movie);
      }
  }
  
  class MovieRequest {
      String name;
      Long directorId
  }
  </code></pre>
  
  <p>As you can see, the <code>create</code> method first loads the director by its id, then creates the new movie and finally saves it. This causes two trips to the database: the first one to retrieve the director and the second one to save the movie.</p>
  
  <p>In this case it's not a big problem, but there could be an entity with lots of relations, which means potentially doing lots of queries to achieve a single insert.</p>
  
  <p><strong>Question</strong>: I would like to save the new movie in a singe database operation. Is there a way to avoid the initial person query? Is there a better way to handle cases like this?</p>