Annotation @Version

1

Using the @Version Annotation, shows this error when trying to update.

  

18: 25: 16.650 [http-nio-8080-exec-84] ERROR   br.com.netsoft.controller.todos.AutomationMonetariaItemController -   Row was updated or deleted by another transaction (or unsaved-value   mapping was incorrect):   [br.netsoft.model.all.additional.content] # 8]

When inserting is working.

It is mapped so

    @Version
    @Column(name = "NR_VERSAO", nullable = false)
    public int getNrVersao() {
        return nrVersao;
    }

Change method

@Transactional
@Repository
public class BaseRepositorio<T> {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @PersistenceContext
    protected EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public T inserir(T objeto) throws Exception {
        this.entityManager.persist(objeto);
        return objeto;
    }

    public T alterar(T objeto) throws Exception {
        return merge(objeto);
    }

    private T merge(T objeto) {
        this.entityManager.detach(objeto);
        this.entityManager.merge(objeto);
        return objeto;
    }
}
    
asked by anonymous 07.01.2018 / 13:49

1 answer

1

@guilherme, adjust your merge method:

private T merge(T objeto) {
    this.entityManager.detach(objeto);
    return this.entityManager.merge(objeto);
}

The entityManager.merge (T entity) method returns the resulting merge object and with the increased version. In your T merge method you are returning the same object you received as the parameter, so with the version value unchanged. When trying to save a second time, the version is deprecated in relation to the database, so Hibernate triggers the exception "Row was updated or deleted by another transaction".

The behavior of the entityManager.persist (T entity) method is already different because it updates the object itself that it receives as a parameter.

    
07.01.2018 / 22:42