Delete data with the @ManyToOne relation

2

How do I delete data with the @ManyToOne relation? It does not give an error, but does not erase the data in the database.

My class Pedido :

public class Pedido extends GenericDomain{

    @Column(nullable = false)
    private Short quantidade;

    @Column(nullable = false, precision = 7, scale = 2)
    private BigDecimal precoParcial;

    @ManyToOne
    @JoinColumn(nullable = false)
    private Produto produto;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(nullable = false)
    private Venda venda;

My class Venda :

public class Venda extends GenericDomain{


       @Column(nullable = false)

    @Temporal(TemporalType.TIMESTAMP)
    private Date horario;

    @Column(nullable = false, precision = 10, scale = 2)
    private BigDecimal precoTotal;

    @ManyToOne
    private Cliente cliente;

    @ManyToOne
    @JoinColumn(nullable = false)
    private Funcionario funcionario;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "venda")
     @Fetch(FetchMode.SUBSELECT)
    @Cascade(CascadeType.DELETE)
    private List<Pedido> pedido= new ArrayList<Pedido>();

In my DAO:

public void excluir(Venda venda, List<Pedido> pedido) {
    Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();
    Transaction transacao = null;

    try {
        transacao = sessao.beginTransaction();      

        for(int posicao = 0; posicao < pedido.size(); posicao++){

            Pedido pedidoVenda = pedido.get(posicao);
            pedidoVenda.setVenda(venda);            
            sessao.delete(sessao.get(Venda.class, pedidoVenda));

        }
        transacao.commit();
    } catch (RuntimeException erro) {
            if (transacao != null) {
                transacao.rollback();
            }
            throw erro;
    } finally {
        sessao.close();
    }
}

}

Bean:

public void excluir(ActionEvent evento) {
    try {
        venda = (Venda) evento.getComponent().getAttributes().get("vendaSelecionado");

        VendaDAO vendaDAO = new VendaDAO();
        vendaDAO.excluir(venda, pedido);
        vendas = vendaDAO.listar();

        Messages.addGlobalInfo(" Venda removido com sucesso");
    } catch (RuntimeException erro) {
        Messages.addFlashGlobalError("Ocorreu um erro ao tentar remover a Venda");
        erro.printStackTrace();
    }
}

XHTML:

<p:commandButton icon="ui-icon-trash" actionListener="#{vendaBean.excluir}"
    update=":mensagem :formListagem:tabela">
    <p:confirm header="Confirmação" message="Deseja excluir a Venda?"
        icon="ui-icon-alert" />

        <f:attribute name="vendaSelecionado" value="#{venda}" />
</p:commandButton>

Here is GenericDomain:

@MappedSuperclass
@SuppressWarnings("serial")
public class GenericDomain implements Serializable{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long codigo;

    public long getCodigo() {
        return codigo;
    }
    public void setCodigo(long codigo) {
        this.codigo = codigo;
    }

    @Override
    public String toString() {
        return String.format("%s[codigo=%d]", getClass().getSimpleName(), getCodigo());
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (int) (codigo ^ (codigo >>> 32));
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        GenericDomain other = (GenericDomain) obj;
        if (codigo != other.codigo)
            return false;
        return true;
    }
    
asked by anonymous 21.12.2016 / 12:51

2 answers

0

If the mapping is running,

It's like this.

objetoPai.getPedido().remove(pedido-a-ser-removido);
sessao.update(objetoPai);

For the remove function to work from the list you must have hashCode and Equals implemented correctly

    
21.12.2016 / 19:29
0

If you want to remove only the product, it would only give update to the object request pointing product as null, the update of Request would remove the product entity, and the Request-Product mapping could not be nullable = false.

But if it is to remove the request as a whole, just remove the delete in the Request entity and cascade @ManyToOne, like this:

@ManyToOne(optional = false, cascade = CascadeType.REMOVE)

    
23.12.2016 / 18:15