Hibernate / JPA - object is an unsaved transient instance

1

Good afternoon people!

When saving a new contract readjustment I have to search for other "similar" contracts to what I'm re-adjusting and readjust them as well.

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

  

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? Here is the code part about 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;
}   
    
asked by anonymous 14.11.2016 / 15:41

1 answer

1

I've solved it. This case is a bit specific, maybe the solution will not serve too many pros, but the error is that CallBack to function uses the merged entity and I was modifying the unmixed entity.

I just passed the reajustarContratosVinculados() method and the merged entity that worked.

if (mergedEntity.getReajustarVinculados().equalsIgnoreCase("S"))
    reajustarContratosVinculados(mergedEntity);
    
14.11.2016 / 18:35