Insert record into a table and use newly generated ID to insert record into related table

0

I have insert where I save a record, and I need to use the result of the value saved in another insert .

Empresa emp = new Empresa();
emp.setId(1);
emp.setNome("Nome da empresa");

repository1.saveAndFlush(emp);

RelacaoEmp relEmp = new RelacaoEmp();
relEmp.setId(100);
relEmp.setIdEmp(1); //O mesmo Id Cadastrado na empresa
relEmp.setTpEmp(10);

repository2.save(relEmp);

When this operation is effective, it says that company 1 does not exist.

Is there any way I can enforce registration of repository1 before running repository2 to not give this problem?

    
asked by anonymous 17.10.2018 / 16:32

1 answer

0
Empresa emp = new Empresa();
Empresa empSalva = new Empresa();

emp.setId(1);
emp.setNome("Nome da empresa");

empSalva = repository1.saveAndFlush(emp);

RelacaoEmp relEmp = new RelacaoEmp();
relEmp.setId(100);
relEmp.setIdEmp(empSalva.getId()); //O mesmo Id Cadastrado na empresa
relEmp.setTpEmp(10);

repository2.save(relEmp);
    
17.10.2018 / 16:55