How to exclude a parent entity without excluding the daughter entities?

Asked

Viewed 190 times

-7

How do I, by Annotations or methods to delete, or effect a update in a parent entity without being obliged to exclude the daughter entity, ex:

public class Produto{

@Id
@GeneratedValue
int id;
//...
@ManyToOne() //fetch.LAZY
Categoria categoria;

}

public class Categoria{

@Id
@GeneratedValue
int id;
//...
@OneToMany(mappedby = "categoria") //fetch.LAZY
Produto produto;

}

We see that my class produto is the daughter class of the operation, the stronger side, which holds the foreign key category, I would like to be able to delete a category, even if it is related to a product, by updating the column CATEGORIA_ID from table to NULL maybe.

But when I try to delete it makes an error:

Constraintviolationexception It is not possible to delete or update a record that has a relationship.

I’ve tried the property ORPHANREMOVAL = FALSE and nothing.

  • 5

    Don’t write in capital letters, because it gives the impression that you are SCREAMING.

  • 4

    Please edit your question to make it clearer and readable, I suggest you read how to format your question

  • sorry friends, I won’t do it again.

1 answer

2


Add nullable=true the mapping of its daughter entity and, in its delete() of the parent entity, before effectively erasing that entity, you have to set null in all children related to it. For example (adapt to your logic, it is just an example):

public void deleteCategoria(int categoriaId) {
    Session currentSession = sessionFactory.getCurrentSession();

    // pesquise a categoria
    Categoria categoria = currentSession.get(Categoria.class, categoriaId);  
    //recupere os produtos        
    List<Produto> produtos = categoria.getProdutos();

    //sete o id de cada produto para null
    for(Produto produto : produtos) {
        produto.setCategoria(null);
    }

    //remova a categoria
    currentSession.remove(categoria);
}
  • Thanks buddy, I’m gonna run the test, big hug !

Browser other questions tagged

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