How to delete a parent entity without excluding child entities?

-6

How do I, by annotations or methods to exclude, or make a update in a parent entity without being forced to delete the child entity, eg

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;

}

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

But when I try to exclude it it generates an error:

  

ConstraintViolationException You can not delete or update a record that has a relationship.

I've tried the NULL property and nothing.

    
asked by anonymous 03.11.2018 / 17:01

1 answer

2

Add nullable=true to the mapping of your child entity and, in its delete() method of the parent entity, before actually deleting this entity, you have to set null to all children related to it. For example (adapt to your logic, 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);
}
    
03.11.2018 / 17:58