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

Asked

Viewed 47 times

0

I have a insert where I save a record, and need to use the result of the saved value 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 effective this operation he says that company 1 does not exist.

Is there any way for me to effect the registration of repository1 before executing the repository2 not to give this problem?

  • This is inside a transaction?

  • See if this helps: https://stackoverflow.com/q/45491551/8133067

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);
  • Have you solved the problem? That’s the solution?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.