removal of related JPA and Hibernate data

Asked

Viewed 56 times

0

I have two classes, Fornecedor and Produto and when I register the Produto and choose a Fornecedor normal sage, but at the time of removing a Produto or Fornecedor related to a Produto nothing happens.

Does anyone know what it can be?

Product class

@Entity
@Table (name="Produto")
public class Produto {

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn (name="idFornecedor")
@Cascade(org.hibernate.annotations.CascadeType.DELETE)
private Fornecedor fornecedor;

Supplier Class

@Entity
@Table (name="Fornecedor")
public class Fornecedor {

@OneToMany (mappedBy="fornecedor", fetch=FetchType.LAZY)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
List<Produto> produtos;

Class Productobean Remove Method

public void RemoverProduto(Produto p) {

    EntityManagerFactory factory = Persistence.createEntityManagerFactory("venda_estoque");
    EntityManager manager = factory.createEntityManager();
    manager.getTransaction().begin();

    ProdutoRepository pr = new ProdutoRepository(manager);
    Produto produto = pr.Remover(p.getId());
    manager.remove(produto);

    manager.getTransaction().commit();
    manager.close();
    factory.close();
}
  • You could add the part of the code that does the removal of these records?

  • put the code remove, thought it would be something with mapping

  • This is the same case: https://answall.com/questions/141690/removendo-itens-de-uma-rela%C3%A7%C3%A3o-onetomany-por-omiss%C3%A3o

  • but in case only the product class that pulls the supplier id, already the supplier class does not have id or list that uses

  • I edited the supplier and product classes by mapping but it is not working

1 answer

0

Next, you may have had the same problem as me. For the JPA removal method along with Entitymanager, you must always merge the object when you do find, like this:

private final static EntityManager manager = ConnectionFactory.getEntityManager();

public T findById2(Class<T> clazz, Long id) {
    manager.getTransaction().begin();
    return manager.find(clazz, id);
}

public void remove(T t) {
    manager.merge(t);
    manager.remove(t);
    manager.getTransaction().commit();
}

Browser other questions tagged

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