Search code examples
springhibernatejpaspring-bootentitymanager

Entity update in EntityManager


Describe briefly the whole situation. I have an entity

public class MovieEntity {
... 
    @OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
    private Set<MovieOtherTitle> otherTitles;
...
}

I save a movie in the database using the JPA Spring Data repository

this.movieRepository.save(movie);

Then I add another title to the film

final MovieOtherTitle movieOtherTitle = new MovieOtherTitle(otherTitle.getTitle(), otherTitle.getCountry());
movieOtherTitle.setMovie(movie);
movieOtherTitle.setUser(user);
this.entityManager.persist(element);

And when I want to display a list of titles for this movie, the list is BLANK

movie.getOtherTitles()

After recompile the application, everything is OK. WHY? It looks as if this entity did not refresh the list in real time. I have to compile the application again and only then you can see the elements in the list.


Solution

  • this.movieRepository.save(movie);
    final MovieOtherTitle movieOtherTitle = new MovieOtherTitle(otherTitle.getTitle(), otherTitle.getCountry());
    movieOtherTitle.setMovie(movie);
    movieOtherTitle.setUser(user);
    
    movie.getOtherTitles().add(movieOtherTitles);
    
    this.movieReoository.save(movie);
    

    So after calling movie.getOtherTitles(); the list will not be empty

    you can get the id of the otherTitle

    movie.getOtherTitles().get(0).getId