0

I have a spring boot rest controller with a post method. I want to fill my two tables at the same time with the same post mapping, knowing that the two have a relationship Many-To-Many.

1- Candidat

@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "candidat_techno", joinColumns = { @JoinColumn(name = "candidat_id") }, 
  inverseJoinColumns = {
        @JoinColumn(name = "techno_id") })

private Set<Techno> techno = new HashSet<>();

public Candidat() {}
@SuppressWarnings("unchecked")
public Candidat(String nom, String prenom, String ecole, String numTel, String mail, String pseudo,
                String roleCible, String typeContrat, String villeRecherchee, List<Techno> techno, Date dateCurrent,)
{...}

2- CandidatController

@RestController
@RequestMapping("/avatar")
public class CandidatController {

    @Autowired
    CandidatDao candidatdao;    
    @Autowired
    TechnoDao technoDao;

    @PostMapping(value = "/add-candidat")
    public Candidat addCandidate(@RequestBody Candidat Candidat) {

        Candidat candidatAdded = candidatdao.save(Candidat);
        return candidatAdded;   
        technodao.save(Candidat.getTechno());
    }
    ...
}

3- CandidatDAO

@Repository
public interface CandidatDao extends JpaRepository<Candidat, String> {}

4- Techno.java

@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "techno")

private Set<Candidat> candidat = new HashSet<Candidat>();

public Techno() {}

5-TechnoController

public class TechnoController {

    @Autowired
    TechnoDao technodao;

    @PostMapping(value = "/add-techno")
    public Techno addCandidate(@RequestBody Techno Techno) {

        Techno technoAdded = technodao.save(Techno);
        return technoAdded;
    }
    ...
}

6- TechnoDao

@Repository
public interface TechnoDao extends JpaRepository<Techno, String> {
    Techno save(Set<Techno> techno);
}

For now I can fill both tables, but with two different post mapping. how to fill both tables (techno and candidate) at the same time ?? like this:

{
    id: 1,
    nom: "smith",
    prenom: "john",
    ecole: "usa",
    numTel: "11111",
    mail: "j@smith",
    pseudo: "JS",
    roleCible: "usa",
    typeContrat: "usa",
    villeRecherchee: "paris",       
    dateCurrent: "2019-10-02",
    techno: [
        {
          id: 1,
          nomTechno: "springBoot"
        },
        {
         id: 2,
         nomTechno: "java"
        }
   ]
}

1 Answers1

0

As far as I know, the @RequestBody can only be consumed once (i.e. you can only have one declaration as param as @RequestBody). Therefore, you either keep the two separated mappings, or you pass both objects as JSON as RequestBody and then in the method you use it to create both objects "manually" based on the JSON data.

I found a great explanation about multiple @RequestBody in mappings here.

Hope this helps.

NDV
  • 56
  • 5