如何同时填写多个表格

时间:2019-10-23 07:27:43

标签: java spring-boot

我有一个带post方法的spring boot rest控制器。我想用相同的帖子映射同时填充我的两个表,知道两个表之间存在多对多关系。

1-候选

@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);
}

目前,我可以填写两个表,但是要使用两个不同的帖子映射。如何同时填写两个表(techno和候选人)?像这样:

{
    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 个答案:

答案 0 :(得分:0)

据我所知,@RequestBody只能被使用一次(即,您只能将一个声明作为@RequestBody作为参数)。因此,您可以保留两个分离的映射,或者将两个对象作为JSON作为RequestBody传递,然后在该方法中使用它根据JSON数据“手动”创建两个对象。

我在映射here中找到了关于多个@RequestBody的很好解释。

希望这会有所帮助。