I have the following entities, and a CrudRepository
for each:
@Entity
class Movie {
@Id Long id;
@Column String name;
@ManyToOne Person director;
}
@Entity
class Person {
@Id Long id;
@Column String name;
}
My controller looks like this:
@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
}
As you can see, the create
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.
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.
Question: 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?