0

I have 2 models: user and movie. I've configured a ManyToMany relationship between them by using:

Movie.java (model):

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(
    name = "movie_user", 
    joinColumns = @JoinColumn(
        name = "movie_id", 
        referencedColumnName = "id"
    ), 
    inverseJoinColumns = @JoinColumn(
        name = "user_id", 
        referencedColumnName = "id"
    )
)

When a movie is added I catch it in the MovieController:

@RequestMapping(value = "/", method = RequestMethod.POST)
public Movie createMovie(@RequestBody Movie movie){
    return movieService.createMovie(movie);
}

In the MovieService:

@Override 
public Movie createMovie(Movie movie) {
    return movieRepository.save(movie);
}

I can add a movie to the movie table without problem, but how do I create a record in the join table?

Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185

1 Answers1

0

In your case User is owner of relationship, so you have to add movie to User object and store user in database. There are a lot of similar questions on SO - for example: @ManyToMany relation not save

Edit: You have to save User object instead of Movie. Add movie to user and store user in database. You have to pass userId to controller to find user which you want to add movie.

Create DTO:

public class UserMovieDTO {
  private Movie movie;
  private Integer userId;
}

Then change your controller and service to:

@RequestMapping(value = "/", method = RequestMethod.POST)
public Movie createMovie(@RequestBody UserMovieDTO dto){
    return movieService.createMovie(dto);
}

@Override 
public Movie createMovie(UserMovieDTO dto) {
    User user = userRepository.findBydId(dto.getUserId());
    user.getMovies().add(dto.getMovie());
    userRepository.save(user);
}

But then you should change your function names to: addMovieToUser or something like this.

piotrb
  • 53
  • 1
  • 7
  • I can find a lot of examples of how to build a relationship, but I cant find any examples of what the code should be in the service or controller to actually save the object. – Peter Boomsma Oct 17 '17 at 18:32