0
I am having problems in the construction of the relations between the models of a project, I have a document that has several subcategories.
When I save a document I want to do a validation, which will create the relationship subcategory-document in the field document
that this model has, but I’m having problems.
I deleted part of the code to point out exactly where the problem happens, which I followed in debug.
Document.java
...
@OneToMany(mappedBy="document", cascade=CascadeType.MERGE)
private Set<Subcategory> subcategories;
Subcategory.java.
...
@ManyToOne()
//necessário, pois se remover isso ao listar o documento ele entra num loop entre as referencias de documento-subcategoria e subcategoria-documento
@JsonIgnore()
private Document document;
Documentserviceimp.java
...
//primeiro chamo a função do save, passando um objeto do tipo documento, e assim irá para a função validade
public Document save(document model) {
return repository.saveAndFlush(validade(model));
}
public Document validade(Document model) {
for(Subcategory subcategory:model.getSubcategories()) {
//pego o objeto
subcategory = subcategoryService.findById(subcategory.getId());
//adiciono uma referência do documento na subcategoria
subcategory.setDocument(model);
//após isso, quero atualizar no modelo de subcategoria esse objeto que adicionei o documento (o do for)
//para isso eu removo o objeto antigo da subcategoria do modelo, entanto isso retorna false, nada é removido mesmo existindo na listagem de subcategorias
model.getSubcategories().remove(subcategory.getId());
//adiciono novamente o objeto atualizado, o objeto fica duplicado, dá erro, o antigo sem o documento e o novo com o documento.
model.addSubcategory(subcategory);
}
}
Without creating that bond between subcategory document and subcategory-document, I cannot correctly associate these.
Any contribution is valid.
That part of the validate is confusing,
– Weslley Barbosa
Good, you do not need to run the Document search by id, just add the reference object, until pq if the result is null, the subcategory will be saved without Document
– Weslley Barbosa
I saw that you have the category removed by the id, before you have the Document saved, I do not understand why, but I think you should change the logic
– Weslley Barbosa