Delete data with the @Manytoone interface

Asked

Viewed 333 times

2

How do I delete data with the interface @ManyToOne? It does not give 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>();

On 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 the 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;
    }
  • The relationship is @ManyToOne as you say in the text or @OneToMany as the code shows?

  • You can give more details about what’s in the classes Venda and Pedido? How is the key to them and how the relationship is done on the other side?

  • is @Onetomany Victor

  • the objective is to delete a sale and the requests it contains, only with the above code it does not erase in the database nor from the error

  • What’s in that one GenericDomain?

  • Victor’s aim is to eliminate the sale and the orders

  • gericdomain has the code that are assigned by Hibernate

Show 2 more comments

2 answers

1

If Voce wants to remove only the product, it would only update the requested object pointing product as null, the Order update would remove the product entity, and the Order-Product mapping could not be nullable=false.

But if it is to remove the request as a whole, just remove give the delete in the Request entity and map with @Manytoone, thus:

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

0

If the mapping this current,

That’s the way it is.

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

To remove it from the list you need to have the hashcode and Equals implemented correctly

  • the hashcode and Equals are well implemented only does not erase in the database nor the error on the screen

  • "well implemented!" has debug and seen that the object is not in the collection? is using Cascade @Cascade(Cascadetype.DELETE), if you are updating, as reported above should be according to the action. @Cascade(Cascadetype.MERGE, Cascadetype.SAVE_UPDATE), equal to the action suffered on the parent object

Browser other questions tagged

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