I am trying to make an application using Spring Boot, MySQL and HTML, but I have a problem. I have two entities, called Establecimiento and Valoracion. My idea is that an establishment can have multiple ratings, but a rating only belongs to one establishment. Therefore, a OneToMany relationship. I attach here how I have it in both entities:
....
@OneToMany(mappedBy = "establecimiento", cascade = CascadeType.PERSIST)
private List<Valoracion> valoraciones;
public void addValoracion(Valoracion valoracion) {
valoraciones.add(valoracion);
valoracion.setEstablecimiento(this);
}
....
@ManyToOne
@JoinColumn(name = "establecimiento_id")
private Establecimiento establecimiento;
Once the entities are established, I want to implement it in the controllers, but the problem is that for an establishment, every time I add a new valuation, it replaces the previous one, so I only have one valuation that is being rewritten. I leave the code below that I have in the controller to make the GET and POST requests.
@RequestMapping(value="/cliente/establecimientos/{id}/nuevaValoracion", method = RequestMethod.GET)
public String nuevaValoracion(@PathVariable Integer id, ModelMap model) {
Establecimiento establecimiento = establecimientoRepository.findById(id).orElse(null);
Valoracion valoracion = new Valoracion(); // crea una nueva instancia de Valoracion
model.put("valoracion", valoracion); // agrega la valoración al modelo
model.put("establecimiento", establecimiento);
return "Cliente/añadirValoracion.html";
}
@RequestMapping(value="/cliente/establecimientos/{id}/anadirValoracion", method = RequestMethod.POST)
public String anadirValoracion(@Valid Valoracion valoracion, @PathVariable Integer id, BindingResult bindingResult, ModelMap mp) throws JSONException {
if (bindingResult.hasErrors()) {
return "Cliente/añadirValoracion.html";
} else {
Establecimiento establecimiento = establecimientoRepository.findById(id).orElse(null);
valoracion.setEstablecimiento(establecimiento);
establecimiento.addValoracion(valoracion);
establecimientoRepository.save(establecimiento);
valoracionRepository.save(valoracion);
mp.put("valoracion", valoracion);
return "redirect:/cliente/establecimientos/" + id;
}
}
I have tried to do this and it only rewrites the valuation. The idea would be that every time you fill in the rating form, a new rating associated with the id of that establishment is added.
Any help would be appreciated.