Error when retrying method after OptimisticLockException - org.postgresql.util.PSQLException: This statement has been closed

浪尽此生 提交于 2019-12-11 00:47:33

问题


I have method:

public void changeItemName(long id, String nmae) {

    Item item = itemDAO.find(id);
    item.setName(name);

    try {
        itemDAO.save(item);
    } catch (RollbackException | OptimisticLockException | StaleStateException e) {
        logger.warn("Retry method after " + e.getClass().getName());
        itemDAO.clear();
        changeItemName(id, name);
    }
}

First, I manually provoke OptimisticLockException by setting higher version, so it goes to catch block, clears EntityManager and retries the method. When retrying, the object/entity is refreshed and has correct version but I get:

javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:86)

Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not update: [com.example.Item#1]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)

Caused by: org.hibernate.exception.GenericJDBCException: could not update: [com.example.Item#1]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)

Caused by: org.postgresql.util.PSQLException: This statement has been closed.
at org.postgresql.jdbc2.AbstractJdbc2Statement.checkClosed(AbstractJdbc2Statement.java:2653)

Database module (using Guice 4.1.0):

public class DbModule extends PrivateModule {

    @Override
    public void configure() {
        install(new JpaPersistModule("persistence-unit").properties(jpaProperties()));

        ...

        Key<PersistFilter> key = Key.get(PersistFilter.class, ExamplePersistenceUnit.class);
        bind(key).to(PersistFilter.class);
        expose(key);
}

Save method implementation (using Hibernate 5.1.0.Final):

@Inject
protected EntityManager entityManager;

@Override
public void save(T entity) {
    entityManager.getTransaction().begin();
    entityManager.persist(entity);
    entityManager.getTransaction().commit();
}

Why does it happen?

UPDATE

After some debugging, I have noticed that:

  • 1st method invocation - I get OptimisticLockException / StaleStateException - that's ok, it was intentionally raised and expected
  • 2nd method invocation, retry, I get Caused by: org.postgresql.util.PSQLException: This statement has been closed - this one was unexpected
  • 3rd method invocation, another retry - it works well and saves to the DB successfully

All 3 times, the same instance of EntityManager entityManager is used.

来源:https://stackoverflow.com/questions/43780675/error-when-retrying-method-after-optimisticlockexception-org-postgresql-util-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!