diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java index f4a14baa44..ac260791fb 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java @@ -92,6 +92,10 @@ public class DefaultRefreshEventListener implements RefreshEventListener { //refresh() does not pass an entityName persister = source.getEntityPersister( event.getEntityName(), object ); id = persister.getIdentifier( object, event.getSession() ); + if ( id == null ) { + throw new HibernateException( "attempted to refresh an instance that is not part of the persistence context yet: " + + infoString( persister, id, source.getFactory() )); + } if ( LOG.isTraceEnabled() ) { LOG.tracev( "Refreshing transient {0}", diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/refresh/RefreshTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/refresh/RefreshTest.java index cdc9265681..0dd05697db 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/refresh/RefreshTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/refresh/RefreshTest.java @@ -6,9 +6,12 @@ import java.util.HashSet; import java.util.LinkedList; import java.util.Set; +import org.hibernate.HibernateException; + import org.hibernate.testing.orm.junit.DomainModel; import org.hibernate.testing.orm.junit.SessionFactory; import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import jakarta.persistence.CascadeType; @@ -27,6 +30,7 @@ import jakarta.persistence.Table; RefreshTest.RealmEntity.class, RefreshTest.RealmAttributeEntity.class, RefreshTest.ComponentEntity.class, + RefreshTest.SimpleEntity.class } ) @SessionFactory @@ -74,6 +78,34 @@ public class RefreshTest { ); } + @Test + public void testRefreshWithNullId(SessionFactoryScope scope) { + Assertions.assertThrows( + HibernateException.class, + () -> { + scope.inTransaction( + session -> { + SimpleEntity se = new SimpleEntity(); + se.setName( "a" ); + session.refresh( se ); + } + ); + }, + "attempted to refresh an instance that is not part of the persistence context yet: [org.hibernate.orm.test.refresh.RefreshTest$SimpleEntity#]" + ); + } + + @Entity(name= "SimpleEntity" ) + public static class SimpleEntity { + @Id + Long id; + String name; + + public void setName(String name) { + this.name = name; + } + } + @Table(name="REALM") @Entity(name = "RealmEntity") public static class RealmEntity {