Hibernate/JPA - Object is an Unsaved Transient instance

Asked

Viewed 422 times

1

Good afternoon people!

When saving a new contract adjustment I have to research other contracts "similar" to what I’m readjusting and readjusting them as well.

For that I was trying to use a callback (saveAfter) after saving the first readjustment in order to readjust the others. The problem is that as the first reset has not yet been committed when I try to save the others occurs the following error:

org.springframework.dao.Invaliddataaccessapiusageexception: org.hibernate.Transientobjectexception: Object is an Unsaved Transient instance - save the Transient instance before merging: [...]

How do I commit all records at once? Below follows the interesting part of the code commenting on the problem:

ReajusteBO.java:

    protected Reajuste saveOrUpdateAfter(Reajuste entity,
        Reajuste mergedEntity, Object... list) throws ApplicationException {

    if (entity.getReajustarVinculados().equalsIgnoreCase("S"))
        reajustarContratosVinculados(entity);

    return super.saveOrUpdateAfter(entity, mergedEntity, list);
}

public Integer reajustarContratosVinculados(Reajuste reajusteOrigem)
        throws ApplicationException {

        List<Contrato> contratos = contratoBO
                .findListByCriteria(Restrictions.eq("cliente", cliente));
        for (Contrato contrato : contratos) {
            if (contrato.getPlano().equals(
                    reajusteOrigem.getContrato().getPlano())) {

                Reajuste r = new Reajuste();
                r.setContrato(contrato);
                mergeEntity(r); // Nesta linha ocorre o erro
                num++;
            }
        }

    return num;
}   
  • Hello! What is the content of the method mergeEntity? How is the mapping of entities Reajuste and Contrato ?

  • Basically it’s just the JPA merge. public ENTITY_TYPE mergeEntity(ENTITY_TYPE Entity){ Return getJpaTemplate(). merge(Entity); }

1 answer

1

I already solved it. This case is a little specific, maybe the solution doesn’t suit the others, but the mistake is that the CallBack to work uses the merged entity and I was modifying the unmixed entity.

All I had to do was pass the method reajustarContratosVinculados() and the merged entity that worked.

if (mergedEntity.getReajustarVinculados().equalsIgnoreCase("S"))
    reajustarContratosVinculados(mergedEntity);

Browser other questions tagged

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