i was trying to build an entity of "Pessoa" for my backend test class, but it requires a "Cidade" type of property, and when i try to pass a new Cidade or instantiate a builder of Cidade to create a new valid one, i get the errors related to sql:
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Referential integrity constraint violation: "FK_PESSOA_CIDADE_ID: PUBLIC.PESSOA FOREIGN KEY(CIDADE_ID) REFERENCES PUBLIC.CIDADE(ID) (1)"; SQL statement: insert into pessoa (apelido, cidade_id, cpf, hobbie, nome, time_coracao) values (?, ?, ?, ?, ?, ?) [23506-200]
https://www.h2database.com/javadoc/org/h2/api/ErrorCode.html
I already know that the error with code 23506 is thrown when trying to insert or update a row that would violate a referential constraint, because the referenced row does not exist.
But what I don't know is what to do to solve it, can someone help?
I have tried putting not yet existing Ids to create a new Cidade, but it didn't work. I have spent already more than 2 hours on this error.
Test class:
@DataJpaTest
@ActiveProfiles("test")
@Log4j2
class PessoaRepositoryTest {
@Autowired
private PessoaRepository pessoaRepository;
@Test
void save_whenSuccessful(){
Pessoa pessoa2BSalva = PessoaCreator.criarPessoa2BSalva();
Pessoa pessoaSalva = this.pessoaRepository.save(pessoa2BSalva);
Assertions.assertThat(pessoaSalva).isNotNull();
Assertions.assertThat(pessoaSalva.getId()).isNotNull();
}
Pessoa2BSalva method:
public static Pessoa criarPessoa2BSalva(){
return Pessoa.builder()
.nome("Roger")
.cpf("54027892300")
.apelido("Rogerinho")
.timeCoracao("Flamengo")
.hobbie("Futebol")
.cidade(CidadeCreator.criarCidadeValida())
.build();
}
CriarCidadeValida method:
public static Cidade criarCidadeValida(){
return Cidade.builder()
.id(1L)
.nome("Formiga")
.estado("MG")
.qtdHabitantes(75000).build();
}
Any type of help is apreciated
CodePudding user response:
So the issue was that I was not inserting a already existing Cidade, so what I did was change the @Test class to save a Cidade and assign to the Pessoa i was trying to save.
And after more than 2 hours of research I found my solution on Spring boot : Referential integrity constraint violation , at @Cristian Colorado answer
Here's my test class:
@Test
void save_whenSuccessful(){
Pessoa pessoa2BSalva = PessoaCreator.criarPessoa2BSalva();
Cidade cidade2BSalva = CidadeCreator.criarCidade2BSalva();
Cidade cidadeSalva = this.cidadeRepository.save(cidade2BSalva);
pessoa2BSalva.setCidade(cidadeSalva);
Pessoa pessoaSalva = this.pessoaRepository.save(pessoa2BSalva);
Assertions.assertThat(pessoaSalva).isNotNull();
Assertions.assertThat(pessoaSalva.getId()).isNotNull();
}