0

I have a mapped list in entity

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

When adding an entity to this list, the object should be automatically assigned an ID

movie.getOtherTitles().add(movieOtherTitle);

idsToAdd.add(Iterables.getLast(movie.getOtherTitles()).getId()); 

https://zapodaj.net/ac2bf2eccf8bf.png.html

However, it turns out that the entity does not receive ID. Why?

  • ID is generated only during persist/merge. – Bedla Nov 26 '17 at 13:45
  • hmmm, I wonder what this "MovieOtherTitle" entity is? I wonder what its `@Id` field is defined as. I wonder what the SQL issued was when performing a `persist` (assuming that happened). –  Nov 26 '17 at 18:44

1 Answers1

0

The entity will recieve an id only after saving or persisting this entity to database. So you need to save the entity to have that id.

In your case you are using Cascade.All where the OtherTitles child entity will be saved/updated also when the Movie entity itself is updated. So you have to update the Movie entity after updating the value of its child entities to save/update the value of these child entities

movie.getOtherTitles().add(movieOtherTitle);
// save the movie here to get the movie with its child entities updated
moveiRepository.save(movie);
idsToAdd.add(Iterables.getLast(movie.getOtherTitles()).getId()); 
Amr Alaa
  • 545
  • 3
  • 7
  • The question was "why". You should address this in your answer. – idmean Nov 26 '17 at 14:59
  • 'why' cause he didn't save the parent entity – Amr Alaa Nov 26 '17 at 15:01
  • @idmean this is an old question https://stackoverflow.com/questions/47487723/entity-update-in-entitymanager/47489901?noredirect=1#comment81948965_47489901 and this is just another question of the same thread. So i don't know why down voted ?!! its my problem now that i have provided an answer for this question ?! – Amr Alaa Nov 26 '17 at 16:24
  • I did not downvote your question. That said, I'm not sure what you're trying to tell, but everyone is free to downvote as (s)he sees fit. – idmean Nov 26 '17 at 17:06