I have mapped one to many as follows
//TourPackage model
@OneToMany(mappedBy = "packages", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Itinerary> itineraries;
public Set<Itinerary> getItineraries() {
return itineraries;
}
in itinerary model
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="packages_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private TourPackage packages;
now my update function, update form returns tourPackage and multiple itinerary, so what I want to do is delete all previous itinerary and insert new ones. Where I have written //null returned
to my knowledge should return all the itinerary of that package but returns null.
@PostMapping("/update-tour-package")
public String updateTourPackage(@ModelAttribute("tourPackage") TourPackage tourPackage, @RequestParam String[] day, @RequestParam String[] itinerary_title, @RequestParam String[] itinerary_description, @RequestParam String[] itinerary_altitude) {
TourPackage tour = this.tourPackageService.saveTourPackage(tourPackage);
this.itineraryRepo.deleteAll(tour.getItineraries());//null returned for itinerary
for (int i = 0; i < day.length; i++) {
Itinerary ite = new Itinerary();
ite.setPackages(tour);
ite.setDay(day[i]);
ite.setTitle(itinerary_title[i]);
ite.setDescription(itinerary_description[i]);
ite.setAltitude(itinerary_altitude[i]);
this.itineraryRepo.save(ite);
}
return "redirect:/";
}
am I doing it right? please point me in right direction. Please comment if I should provide more context to the question.
Because unless you have config elsewhere to set an existing TourPackage as the model object, @ModelAttribute("tourPackage") TourPackage tourPackage
will be a new instance.
If you want to modify an existing instance then send through a hidden field with the ID and add a method inn your controller:
@ModelAttribute
public TourPackage getTourPackage(@RequestParam(name = "tourPckageId", required = false) Long id){
//load from repo if id is not null or otherwise new instance
}
Now the updateTourPackage method will receive the existing instance returned by the above.
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-methods