I got an entity B bound by a ManyToOne with another Entity A. Writing add method in its controller I obviously pass a field of an Instance of A as a parameter, from which I select the whole object to extract its ID that I use as the key for the relationship. If the instance of A I'm trying to select is non-existent, I want it to be created (the field I'm passing as a parameter is enough for its constructor). Can I do that without instantiating Controller A inside Controller B? It seems weird...
UPDATE I rewrote most part of my project, thanks to the hints by @Artur Vakhrameev
I created a service for every entities and instantiated one of them inside the other one. This is the service for the "many side" relationship entity
@Transactional
@Service
public class LineaService {
@Autowired
private LineaRepository lineaRepo;
@Autowired
private MarcaService marcaService;
public Linea create(Linea linea) {
Linea nuovaLinea = new Linea();
nuovaLinea.setNome(linea.getNome());
if (marcaService.findByName(linea.getMarca().getNome()) == null)
nuovaLinea.setMarca(marcaService.create(linea.getMarca()));
else
nuovaLinea.setMarca(linea.getMarca());
lineaRepo.save(nuovaLinea);
nuovaLinea.getMarca().addLinea(nuovaLinea);
return nuovaLinea;
}
And this is now the simple add
postmapping in my controller, stripped of all the business logic
@PostMapping("/add")
public String aggiungiLinea(Linea linea) {
lineaService.create(linea);
return "redirect:list";
}
UPDATE 2 (this one seems to work as expected)
public Linea create(Linea linea) {
Marca marcaAssociata = marcaService.findByName(linea.getMarca().getNome());
if (marcaAssociata == null)
linea.setMarca(marcaService.create(linea.getMarca()));
else
linea.setMarca(marcaAssociata);
return lineaRepo.save(linea);
}