Erro violação de chave estrangeira

93 views
Skip to first unread message

Inaldo Brandão

unread,
Feb 29, 2016, 12:39:39 PM2/29/16
to java.ce
Galera, Boa Madrugada !

Estou com um erro que não estou conseguindo resolver. Irei anexar as classes para ajudar vcs, mas é o seguinte. Tenho a classe venda e a linha da venda, sendo assim tenho uma foreign key linha da venda com o código da venda. Quando vou deletar um registro, é lançado o erro de violação de chave estrangeira, estou usando hibernate, minha classe está anotada utilizando o CascadeType.ALL, já procurei soluções na internet, e nada, não consegui resolver. Então espero contar com vces. Muito grato desde já !


att,

Inaldo Brandão
HashCode | Software Developer
AbstractRepository.txt
index jsp.txt
SaleModel.txt
SaleLineModel.txt
SaleBusiness.txt
SaleController.txt
SaleLineController.txt
SaleRepository.txt
o erro.txt

Programador Java

unread,
Feb 29, 2016, 1:17:31 PM2/29/16
to jav...@googlegroups.com
ERROR: update or delete on table "orders" violates foreign key constraint "fk_fcace3p6jn1fphcfyl306st6b" on table "order_lines"
  Detalhe: Key (id)=(1) is still referenced from table "order_lines".

Essa tabela order_lines tá mapeada na aplicação?

--
Você recebeu essa mensagem porque está inscrito no grupo "java.ce" dos Grupos do Google.
Para cancelar inscrição nesse grupo e parar de receber e-mails dele, envie um e-mail para javace+un...@googlegroups.com.
Para postar nesse grupo, envie um e-mail para jav...@googlegroups.com.
Acesse esse grupo em https://groups.google.com/group/javace.
Para mais opções, acesse https://groups.google.com/d/optout.

Marcus Mazzo Laprano

unread,
Feb 29, 2016, 1:17:32 PM2/29/16
to jav...@googlegroups.com
Você disse estar usando hibernate, porque teu Delete é SQL? 

Por isso da erro de integridade. Se vc quiser deletar pelo hibernate só chamar o delete do objeto org.hibernate.Session [session.delete(sale)].

Se estiver implementando JPA basta chamar o remove [em.remove(sale)]




Marcus Mazzo Laprano
Analista / Desenvolvedor Java
http://www.marcusmazzo.com.br

Em 25 de fevereiro de 2016 00:50, Inaldo Brandão <inal...@gmail.com> escreveu:

--

Gilmario Batista

unread,
Mar 1, 2016, 8:51:12 AM3/1/16
to jav...@googlegroups.com
Tive esse problema recente.
Se você que fazer delete tipo cascata deve utilizar a anotação onDelete
e verifique se a sua tabela foi criada com a instrução 'ON DELETE CASCADE'
é isso que vai fazer o delete em cascata.





@OnDelete(action = OnDeleteAction.CASCADE)

ex:



@Entity
@Table(name = "sale_lines")
@SequenceGenerator(name = "sale_line_seq", sequenceName = "sale_line_seq")
public class SaleLine {
 
    @Id
    @GeneratedValue(generator = "sale_line_seq", strategy = GenerationType.AUTO)
    private Long id;
 
    @ManyToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "product_id", nullable = false, updatable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Product product;
 
    private Integer quantity;
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public Product getProduct() {
        return product;
    }
 
    public void setProduct(Product product) {
        this.product = product;
    }
 
    public Integer getQuantity() {
        return quantity;
    }
 
    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }
 
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((product == null) ? 0 : product.hashCode());
        result = prime * result
                + ((quantity == null) ? 0 : quantity.hashCode());
        return result;
    }
 
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        SaleLine other = (SaleLine) obj;
        if (product == null) {
            if (other.product != null)
                return false;
        } else if (!product.equals(other.product))
            return false;
        if (quantity == null) {
            if (other.quantity != null)
                return false;
        } else if (!quantity.equals(other.quantity))
            return false;
        return true;
    }
 
}



Inaldo Brandão

unread,
Mar 3, 2016, 3:42:33 PM3/3/16
to java.ce
Consegui resolver antes de aprovarem a postagem, era exatamente o que o Gilmario Batista disse. Obrigado galera !
Reply all
Reply to author
Forward
0 new messages