Hello,
I'm having problems when retrying to insert a new record in database. I do a persist and when the container (CMT) commits the transaction they throw one RollbackException. Then, I catch this exception and try to insert again. But, this exception is throw:
Quote:
org.hibernate.PersistentObjectException: detached entity passed to persist: visualcontrol.model.entity.PedidoVendaItem
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:79)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:609)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:601)
The code in EJB is the following:
Code:
public void incluir(PedidoVenda pedido) throws ValorPropriedadeInvalidaException{
if (pedido != null) {
if (pedido.getNaturezaOperacao() == null) {
pedido.setNaturezaOperacao(naturezaOperacaoPadrao(pedido));
}
try {
// Get a new value to avoid violation of unique key
pedido.setNumero(getProximoNumero());
em.persist(pedido);
atualizarEstoque(pedido);
} catch (PersistenceException ex) {
throw new VisualControlException("Não foi possível incluir o pedido.", ex);
}
} else {
throw new IllegalArgumentException("Pedido não pode ser nulo. Inclusão cancelada.");
}
}
The client for this code is:
Code:
for (int i = 0; i < DBUtils.RETRY.length && !isIncluido(); i++) {
try {
pedidoFacade.incluir(getPedidoVenda());
setIncluido(true);
} catch (EJBException ex) {
// Catch the violation of unique key and try again. The method incluir gets a new number
if (i < DBUtils.RETRY.length && ex.getCausedByException() instanceof RollbackException) {
try {
pedidoVenda.setId(0); // Se não commitou zera o id para o hibernate não achar que o objeto ja esta salvo
Thread.currentThread().sleep((long) (DBUtils.RETRY[i] * (1.0 + Math.random())));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
throw new VisualControlException("Erro ao salvar pedido de venda", ex);
}
}
}
Why hibernate is not saving when I try to insert again? The object was not persisted for the first time, because a RollbackException (violation of unique key).
How can I solve this?
Hibernate version:3.2
Name and version of the database you are using: Firebird 1.5.4