java - Issue with `refresh` after upgrading from Hibernate 5 to 6 - Stack Overflow

admin2025-04-16  1

After upgrading Hibernate from 5 to 6, I started encountering exceptions in a central part of my code.

I can no longer refresh a newly persisted entity. Previously, my code worked like this:

public <T extends IdentifiableObject> T create(T t) {
    this.entityManager.persist(t);
    this.entityManager.flush();
    this.entityManager.refresh(t);
    return t;
}

However, now it throws the following exception:

org.hibernate.TransientObjectException: Instance was not associated with this persistence context

Without the refresh, not everything seems to be correctly set from the database (though the ID is populated correctly).

I also tried retrieving the instance using find:

this.entityManager.persist(t);
this.entityManager.flush();
Object primaryKey = t.getId();
t = (T) this.entityManager.find(t.getClass(), primaryKey);
this.entityManager.refresh(t);

But this still results in the same exception on refresh. The entity appears to be the same object that was persisted.

Using merge instead of refresh is not a good solution because it overrides values in the database that were not yet correctly loaded. In fact, it raises an exception due to a NULL constraint violation.

I was able to work around the issue by clearing the EntityManager, but I’m almost certain this will introduce unwanted side effects.

Does anyone have any ideas on how to resolve this?

If it helps, the database is PostgreSQL. I also ran tests using an H2 database, where refresh works without issues.

转载请注明原文地址:http://www.anycun.com/QandA/1744759995a87224.html