Exclusão de Compras e ItensCompra

6 respostas
A

Bom dia,

bem, estou com um problema para excluir uma compra e seus itens de compra, nunca fiz isso, e o que encontrei na internet não ajudou, ou não entendi.

Tenho a Tabela 'CompraEPI' e a tabela 'ItensCompra'

Persistência de CompraEPI:
@Table (name = "CompraEpi")
public class CompraEpi {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer idComprarEpi;

@Column (name= "notaFiscal")
private String notaFiscal;

@Column (name= "dtCompra")
private String dtCompra;

@Column (name= "vlTotal")
private String vlTotal;

@ManyToOne
private Fornecedor fornecedor; 

@OneToMany(fetch= FetchType.LAZY, mappedBy="compraEpi")
private List<ItensCompra> listaItensCompra;
//MÉTODOS GET / SET
Persistência de ItensCompra:
@Table(name = "ItensCompra")
public class ItensCompra {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;

@Column (name = "qtEpi")
private String qtEpi;

@Column (name = "vlUnitario")
private String vlUnitario;

@ManyToOne
private Epi epi;

@ManyToOne
private CompraEpi compraEpi; 
//MÉTODOS GET / SET
Método Excluir DAO:
//MÉTODO DE EXCLUSÃO DE DADOS NA TABELA CompraEpi
public void excluir(CompraEpi compraEpi) {
Transaction transacao = (Transaction) sessao.beginTransaction();
sessao.delete(compraEpi);
transacao.commit();

//MÉTODO DE EXCLUSÃO DE DADOS NA TABELA ItensCompra
public void excluir(ItensCompra itensCompra) {
Transaction transacao = (Transaction) sessao.beginTransaction();
sessao.delete(itensCompra);
transacao.commit();
EXCLUSÃO:
// COMANDO PARA EXCLUIR REGISTRO
ComprarEpiDAO comprarEpiDAO = new ComprarEpiDAO();
CompraEpi compraEpi = comprarEpiDAO.buscarPorCodigo(Integer.parseInt(idComprarEpi.getText())); 
compraEpi.setNotaFiscal(notaFiscal.getText());
compraEpi.setVlTotal(valorTotalCompra.getText());
compraEpi.setDtCompra(dtCompra.getText());
compraEpi.setFornecedor((Fornecedor) consultaNomeFornecedor.getSelectedItem());

comprarEpiDAO.excluir(compraEpi);

List<ItensCompra> lista = compraEpi.getListaItensCompra();
ItensCompraDAO itensCompraDAO = new ItensCompraDAO();

for (ItensCompra itensCompra : lista){
itensCompraDAO.excluir(itensCompra);
}

int linhas = tabelaCompra.getRowCount();
for (int i = 0; i < linhas; i++) {
ItensCompra itensCompra = new ItensCompra();
itensCompra.setCompraEpi(compraEpi);

itensCompra.setEpi((Epi) tabelaCompra.getValueAt(i, 0));
Object quantidade = tabelaCompra.getValueAt(i, 1);
itensCompra.setQtEpi(quantidade.toString());
Object valor = tabelaCompra.getValueAt(i, 2);
itensCompra.setVlUnitario(valor.toString());

itensCompraDAO.excluir(itensCompra);
}// fecha for

ERRO:
8537 [AWT-EventQueue-0] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 547, SQLState: 23000
8537 [AWT-EventQueue-0] ERROR org.hibernate.util.JDBCExceptionReporter - The DELETE statement conflicted with the REFERENCE constraint "FK84500E1DA7FEDF14". The conflict occurred in database "UniOcupSystem", table "dbo.ItensCompra", column 'compraEpi_idComprarEpi'.
8538 [AWT-EventQueue-0] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: could not delete: [persistencia.CompraEpi#5]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)

at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPers
ister.java:2569)
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPers
ister.java:2725)
at org.hibernate.action.EntityDeleteAction.execute(EntityDeleteAction.java:97)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:172)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(Abstract
FlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListe
ner.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at dao.ComprarEpiDAO.excluir(ComprarEpiDAO.java:47)
at telas.PesquisarCompra.btnExcluirActionPerformed(PesquisarCompra.java:893)
at telas.PesquisarCompra.access$2100(PesquisarCompra.java:23)
at telas.PesquisarCompra$23.actionPerformed(PesquisarCompra.java:555)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.jav
a:236)
at java.awt.Component.processMouseEvent(Component.java:6267)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6032)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269
)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174
)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The DELETE statement conflicted with the REFERENCE constraint "FK84500E1DA7FEDF14". The conflict occurred in database "UniOcupSystem", table "dbo.ItensCompra", column 'compraEpi_idComprarEpi'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerE
xception.java:196)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement
.java:1454)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStateme
nt(SQLServerPreparedStatement.java:388)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:338)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnect
ion.java:1416)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatemen
t.java:185)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatem
ent.java:160)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerP
reparedStatement.java:306)
at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:46)
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPers
ister.java:2548)
... 39 more

6 Respostas

nel

Oi!

Você está tentando remover uma tabela que possui sua chave primária como referência em outra. Portanto, primeiro exclua a tabela que possui a referência para que deseja excluir, em seguida, exclua a secundaria. Pode ver, o erro acusa problema de Chave Estrangeira, ou seja, que ela está sendo referenciada em outra tabela.

Abraços.

I

Isso ai, basta fazer seu laço para exclusão dos ItensCompra antes de excluir sua Compra.

leoramos

Aproveita que tá usando Hibernate e mapeia certinho:

@OneToMany(teu mapeamento, ok, bla bla bla) @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)

Aí quando tu exclui o pai, os filhos vão pro estanho junto…

Abraço!

nel

leoramos:
Aproveita que tá usando Hibernate e mapeia certinho:

@OneToMany(teu mapeamento, ok, bla bla bla) @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)

Aí quando tu exclui o pai, os filhos vão pro estanho junto…

Abraço!

Era isso mesmo que eu queria falar mas havia me esquecido.
Estou uns meses sem usar JPA e acabo esquecendo alguns detalhes, mas realmente, se fizer o mapeamento correto, excluindo o Pai qualquer filho será excluido automaticamente.

Abraços.

A

Boa tarde, valeu pela dica, ficou assim meu mapeamento e deu certinho:

@OneToMany (cascade={CascadeType.REMOVE}, fetch= FetchType.LAZY, mappedBy="RegistraExame")
private List<ItensTuss> listaItensTuss;

assim excluo o Pai e seus filhos.

abraços
Aline

nel

alinelozano:
Boa tarde, valeu pela dica, ficou assim meu mapeamento e deu certinho:

@OneToMany (cascade={CascadeType.REMOVE}, fetch= FetchType.LAZY, mappedBy="RegistraExame")
private List<ItensTuss> listaItensTuss;

assim excluo o Pai e seus filhos.

abraços
Aline

Oi!
Que bom, podes substituir o CascadeType.REMOVE para ALL, assim, basta persistir, atualizar, remover o pai que os seus respectivos filhos sofrem as mesmas alterações.
Abraços.

Criado 16 de junho de 2011
Ultima resposta 16 de jun. de 2011
Respostas 6
Participantes 4