0
Guys I’m having difficulty in relationships with Hibernate, I have a 1:N relationship between Provider and Address (1 provider may have N addresses). My problem is this, when I try to persist a provider it also tries to persist the address (which is right), the problem is that it ta trying to persist the address without putting the Provider id in the foreing key column that I defined with not null.
//Classe de Prestador
@OneToMany(mappedBy = "prestador", cascade = CascadeType.ALL)
private List<EnderecoEntity> enderecos;
//Classe de Endereço
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fk_prestador")
private PrestadorEntity prestador;
//Ao chamar o repositorio para salvar o prestador ele executa os seguintes comandos
Hibernate: insert into prestador (nome, path_foto) values (?, ?)
Hibernate: insert into endereco (cep, cidade, estado, logradouro, numero) values (?, ?, ?, ?, ?)
//Erro que está acontecendo informando que a fk não tem um valor padrão (porque está null)
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1364, SQLState: HY000
o.h.engine.jdbc.spi.SqlExceptionHelper : Field 'fk_prestador' doesn't have a default value
{
"nome": "Teste",
"enderecos": [
{
"cep": 999999,
"logradouro": "Rua Teste",
"numero": 4,
"cidade": "Maceió",
"estado": "Alagoas"
}
]
}
put its complete entity, does not need the get and set but the attributes are indispensable. what was the ID generation strategy?
– André Martins
In both classes the id generation is made by the @Id and @Generatedvalue(IDENTITY) annotation... the attribute is a Long
– W. Silva
Does your system use any DDL script to create the database? If so, you have defined on it that the provider id will be auto-generated?
– StatelessDev
@Statelessdev I do not use any sript to create the base... I created it myself, put the id’s as auto_increment and in the address table added the provider fk with FOREIGN KEY (fk_provider) REFERENCES provider(id)
– W. Silva