How to save JPA/Spring Data entity that contains a list of other entities without having to look them all up?

StackOverflow https://stackoverflow.com/questions/13215576

  •  30-07-2021
  •  | 
  •  

Question

Lets say you had an entity called Bus. In that entity you have a list of passengers. In the UI you select the passengers that will be in the Bus. After all the passengers have been added to the bus you submit the page. Server side you get The Bus entity and you get a list of ids that represents the passengers. Do I really have to look up all these passengers and set the list of passengers on the Bus before I save the Bus. I haven't changed any information about the passengers themselves and would hate to have to do the database hit if its not needed.

Searching around I have seen people using the entity manager find() to do this, but I am not sure how I would do that with spring-data.

Ideally it would be nice to just set this list of ids on the json object I send up and use some annotation on the Bus entity so that it knows to expect ids when saving the passenger list on the Bus entity.

I am fairly new to JPA so feel free to point me to the correct words to search on google. I am just not sure how to go about doing something like this.

Was it helpful?

Solution

With spring data it uses the merges so all I had to do is save the bus with a newly created list of passengers that only had the id set on them. No need to look them up, just create a new object and set the id on it and then save. It is as easy as that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top