@@ -163,6 +163,7 @@ protected boolean readSize() {
163163 session .getPersistenceContextInternal ().getCollectionEntry ( this );
164164 if ( entry != null ) {
165165 final CollectionPersister persister = entry .getLoadedPersister ();
166+ checkPersister ( initialized , persister );
166167 if ( persister .isExtraLazy () ) {
167168 // TODO: support for extra-lazy collections was
168169 // dropped so this code should be obsolete
@@ -330,6 +331,7 @@ protected Boolean readIndexExistence(final Object index) {
330331 () -> {
331332 final CollectionEntry entry = session .getPersistenceContextInternal ().getCollectionEntry ( this );
332333 final CollectionPersister persister = entry .getLoadedPersister ();
334+ checkPersister ( initialized , persister );
333335 if ( persister .isExtraLazy () ) {
334336 if ( hasQueuedOperations () ) {
335337 session .flush ();
@@ -352,6 +354,7 @@ protected Boolean readElementExistence(final Object element) {
352354 () -> {
353355 final CollectionEntry entry = session .getPersistenceContextInternal ().getCollectionEntry ( this );
354356 final CollectionPersister persister = entry .getLoadedPersister ();
357+ checkPersister ( initialized , persister );
355358 if ( persister .isExtraLazy () ) {
356359 if ( hasQueuedOperations () ) {
357360 session .flush ();
@@ -398,6 +401,7 @@ public Object doWork() {
398401 session .getPersistenceContextInternal ()
399402 .getCollectionEntry ( AbstractPersistentCollection .this );
400403 final CollectionPersister persister = entry .getLoadedPersister ();
404+ checkPersister ( initialized , persister );
401405 isExtraLazy = persister .isExtraLazy ();
402406 if ( isExtraLazy ) {
403407 if ( hasQueuedOperations () ) {
@@ -652,6 +656,12 @@ private void throwLazyInitializationException(String message) {
652656 );
653657 }
654658
659+ public static void checkPersister (boolean collectionInitialized , CollectionPersister persister ) {
660+ if ( !collectionInitialized && persister == null ) {
661+ throw new HibernateException ( "Attempt to access a lazy collection from within an illegal context (e.g. a lifecycle listener method)" );
662+ }
663+ }
664+
655665 protected final void setInitialized () {
656666 this .initializing = false ;
657667 this .initialized = true ;
0 commit comments