Annotation

Asked

Viewed 100 times

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.Updatemanetariaitemcontroller - Row was updated or Deleted by Another transaction (or Unsaved-value Mapping was incorrect) : [br.com.netsoft.model.todos.Updatemanetariaitementity#8]

When you insert is working.

Is mapped like this

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

Method of altering

@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;
    }
}
  • The problem seems to be before this. Who calls this merge method? but if it were you I would use the original behavior of merge (unused detach).

1 answer

1

@Guilherme, adjust your merge method:

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

The method entityManager.merge(T Entity) returns the resulting merge object with the incremented version. In your method T merge(T object) you are returning the same object you received as a parameter, therefore with the version value unchanged. When trying to save a second time, the version is lagged from the bank and therefore Hibernate fires the Exception of "Row was updated or Deleted by Another transaction".

The behaviour of the method entityManager.persist(T Entity) is different because it updates the object itself that it receives as parameter.

  • Thank you. I imagined this. But how to do the right ? I broke my head and I could not advance.

  • Badaro, no good, same mistake.

  • @William, put a breakpoint in the change method to check if nrVersao is coming up with the correct value. If not. some point in your routine is changing it or using a defaulted copy of the entity.

  • Then I have to check the value before changing. I will check.

  • Didn’t work....

Browser other questions tagged

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