4 * Hibernate, Relational Persistence for Idiomatic Java
6 * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
7 * indicated by the @author tags or express copyright attribution
8 * statements applied by the authors. All third-party contributions are
9 * distributed under license by Red Hat Inc.
11 * This copyrighted material is made available to anyone wishing to use, modify,
12 * copy, or redistribute it subject to the terms and conditions of the GNU
13 * Lesser General Public License, as published by the Free Software Foundation.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this distribution; if not, write to:
22 * Free Software Foundation, Inc.
23 * 51 Franklin Street, Fifth Floor
24 * Boston, MA 02110-1301 USA
26 package org
.hibernate
.collection
.internal
;
28 import java
.io
.Serializable
;
29 import java
.lang
.reflect
.Field
;
30 import java
.util
.ArrayList
;
31 import java
.util
.Collection
;
32 import java
.util
.Collections
;
33 import java
.util
.HashSet
;
34 import java
.util
.Iterator
;
35 import java
.util
.List
;
36 import java
.util
.ListIterator
;
38 import javax
.naming
.NamingException
;
40 import org
.hibernate
.AssertionFailure
;
41 import org
.hibernate
.HibernateException
;
42 import org
.hibernate
.LazyInitializationException
;
43 import org
.hibernate
.Session
;
44 import org
.hibernate
.collection
.spi
.PersistentCollection
;
45 import org
.hibernate
.engine
.internal
.ForeignKeys
;
46 import org
.hibernate
.engine
.spi
.CollectionEntry
;
47 import org
.hibernate
.engine
.spi
.EntityEntry
;
48 import org
.hibernate
.engine
.spi
.SessionFactoryImplementor
;
49 import org
.hibernate
.engine
.spi
.SessionImplementor
;
50 import org
.hibernate
.engine
.spi
.Status
;
51 import org
.hibernate
.engine
.spi
.TypedValue
;
52 import org
.hibernate
.internal
.SessionFactoryRegistry
;
53 import org
.hibernate
.internal
.util
.MarkerObject
;
54 import org
.hibernate
.internal
.util
.collections
.EmptyIterator
;
55 import org
.hibernate
.internal
.util
.collections
.IdentitySet
;
56 import org
.hibernate
.persister
.collection
.CollectionPersister
;
57 import org
.hibernate
.persister
.entity
.EntityPersister
;
58 import org
.hibernate
.pretty
.MessageHelper
;
59 import org
.hibernate
.type
.Type
;
60 import org
.jboss
.logging
.Logger
;
62 import eu
.etaxonomy
.cdm
.api
.application
.CdmApplicationRemoteConfiguration
;
63 import eu
.etaxonomy
.taxeditor
.remoting
.CdmEagerLoadingException
;
64 import eu
.etaxonomy
.taxeditor
.service
.ICachedCommonService
;
65 import eu
.etaxonomy
.taxeditor
.service
.CachedCommonServiceImpl
.CollectionField
;
68 * Base class implementing {@link org.hibernate.collection.spi.PersistentCollection}
72 public abstract class AbstractPersistentCollection
implements Serializable
, PersistentCollection
{
73 private static final Logger log
= Logger
.getLogger( AbstractPersistentCollection
.class );
75 private static final long serialVersionUID
= -7238232378593030571L;
77 private transient SessionImplementor session
;
78 private boolean initialized
;
79 private transient List
<DelayedOperation
> operationQueue
;
80 private transient boolean directlyAccessible
;
81 private transient boolean initializing
;
83 private int cachedSize
= -1;
86 private Serializable key
;
87 // collections detect changes made via their public interface and mark
88 // themselves as dirty as a performance optimization
89 private boolean dirty
;
90 private Serializable storedSnapshot
;
92 private String sessionFactoryUuid
;
93 private boolean specjLazyLoad
= false;
96 public final String
getRole() {
101 public final Serializable
getKey() {
106 public final boolean isUnreferenced() {
111 public final boolean isDirty() {
116 public final void clearDirty() {
121 public final void dirty() {
126 public final Serializable
getStoredSnapshot() {
127 return storedSnapshot
;
130 //Careful: these methods do not initialize the collection.
133 * Is the initialized collection empty?
136 public abstract boolean empty();
139 * Called by any read-only method of the collection interface
141 protected final void read() {
146 * Called by the {@link Collection#size} method
148 @SuppressWarnings({"JavaDoc"})
149 protected boolean readSize() {
150 if ( !initialized
) {
151 if ( cachedSize
!= -1 && !hasQueuedOperations() ) {
155 // In remoting we are sure that session is null
156 // both when using property paths and switching off conversations
157 if(session
== null && remoting
) {
158 log
.info("--> readSize, of " + getRole() + " with key " + getKey());
161 boolean isExtraLazy
= withTemporarySessionIfNeeded(
162 new LazyInitializationWork
<Boolean
>() {
164 public Boolean
doWork() {
165 CollectionEntry entry
= session
.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection
.this );
167 if ( entry
!= null ) {
168 CollectionPersister persister
= entry
.getLoadedPersister();
169 if ( persister
.isExtraLazy() ) {
170 if ( hasQueuedOperations() ) {
173 cachedSize
= persister
.getSize( entry
.getLoadedKey(), session
);
181 throwLazyInitializationExceptionIfNotConnected();
196 public static interface LazyInitializationWork
<T
> {
200 private <T
> T
withTemporarySessionIfNeeded(LazyInitializationWork
<T
> lazyInitializationWork
) {
201 SessionImplementor originalSession
= null;
202 boolean isTempSession
= false;
203 boolean isJTA
= false;
205 if ( session
== null ) {
206 if ( specjLazyLoad
) {
207 session
= openTemporarySessionForLoading();
208 isTempSession
= true;
211 throwLazyInitializationException( "could not initialize proxy - no Session" );
214 else if ( !session
.isOpen() ) {
215 if ( specjLazyLoad
) {
216 originalSession
= session
;
217 session
= openTemporarySessionForLoading();
218 isTempSession
= true;
221 throwLazyInitializationException( "could not initialize proxy - the owning Session was closed" );
224 else if ( !session
.isConnected() ) {
225 if ( specjLazyLoad
) {
226 originalSession
= session
;
227 session
= openTemporarySessionForLoading();
228 isTempSession
= true;
231 throwLazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
235 if ( isTempSession
) {
236 // TODO: On the next major release, add an
237 // 'isJTA' or 'getTransactionFactory' method to Session.
238 isJTA
= session
.getTransactionCoordinator()
239 .getTransactionContext().getTransactionEnvironment()
240 .getTransactionFactory()
241 .compatibleWithJtaSynchronization();
244 // Explicitly handle the transactions only if we're not in
245 // a JTA environment. A lazy loading temporary session can
246 // be created even if a current session and transaction are
247 // open (ex: session.clear() was used). We must prevent
248 // multiple transactions.
249 ( ( Session
) session
).beginTransaction();
252 session
.getPersistenceContext().addUninitializedDetachedCollection(
253 session
.getFactory().getCollectionPersister( getRole() ),
259 return lazyInitializationWork
.doWork();
262 if ( isTempSession
) {
263 // make sure the just opened temp session gets closed!
266 ( ( Session
) session
).getTransaction().commit();
268 ( (Session
) session
).close();
270 catch (Exception e
) {
271 log
.warn( "Unable to close temporary session used to load lazy collection associated to no session" );
273 session
= originalSession
;
278 private SessionImplementor
openTemporarySessionForLoading() {
279 if ( sessionFactoryUuid
== null ) {
280 throwLazyInitializationException( "SessionFactory UUID not known to create temporary Session for loading" );
283 SessionFactoryImplementor sf
= (SessionFactoryImplementor
)
284 SessionFactoryRegistry
.INSTANCE
.getSessionFactory( sessionFactoryUuid
);
285 return (SessionImplementor
) sf
.openSession();
288 protected Boolean
readIndexExistence(final Object index
) {
289 if ( !initialized
) {
290 // In remoting we are sure that session is null
291 // both when using property paths and switching off conversations
292 if(session
== null && remoting
) {
293 log
.info("--> readIndexExistence, of " + getRole() + " with key " + getKey());
296 Boolean extraLazyExistenceCheck
= withTemporarySessionIfNeeded(
297 new LazyInitializationWork
<Boolean
>() {
299 public Boolean
doWork() {
300 CollectionEntry entry
= session
.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection
.this );
301 CollectionPersister persister
= entry
.getLoadedPersister();
302 if ( persister
.isExtraLazy() ) {
303 if ( hasQueuedOperations() ) {
306 return persister
.indexExists( entry
.getLoadedKey(), index
, session
);
315 if ( extraLazyExistenceCheck
!= null ) {
316 return extraLazyExistenceCheck
;
323 protected Boolean
readElementExistence(final Object element
) {
324 if ( !initialized
) {
325 // In remoting we are sure that session is null
326 // both when using property paths and switching off conversations
327 if(session
== null && remoting
) {
328 log
.info("--> readElementExistence, of " + getRole() + " with key " + getKey());
332 Boolean extraLazyExistenceCheck
= withTemporarySessionIfNeeded(
333 new LazyInitializationWork
<Boolean
>() {
335 public Boolean
doWork() {
336 CollectionEntry entry
= session
.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection
.this );
337 CollectionPersister persister
= entry
.getLoadedPersister();
338 if ( persister
.isExtraLazy() ) {
339 if ( hasQueuedOperations() ) {
342 return persister
.elementExists( entry
.getLoadedKey(), element
, session
);
351 if ( extraLazyExistenceCheck
!= null ) {
352 return extraLazyExistenceCheck
;
359 protected static final Object UNKNOWN
= new MarkerObject( "UNKNOWN" );
361 protected Object
readElementByIndex(final Object index
) {
362 if ( !initialized
) {
363 // In remoting we are sure that session is null
364 // both when using property paths and switching off conversations
365 if(session
== null && remoting
) {
366 log
.info("--> readElementByIndex, of " + getRole() + " with key " + getKey());
370 class ExtraLazyElementByIndexReader
implements LazyInitializationWork
{
371 private boolean isExtraLazy
;
372 private Object element
;
375 public Object
doWork() {
376 CollectionEntry entry
= session
.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection
.this );
377 CollectionPersister persister
= entry
.getLoadedPersister();
378 isExtraLazy
= persister
.isExtraLazy();
380 if ( hasQueuedOperations() ) {
383 element
= persister
.getElementByIndex( entry
.getLoadedKey(), index
, session
, owner
);
392 ExtraLazyElementByIndexReader reader
= new ExtraLazyElementByIndexReader();
393 //noinspection unchecked
394 withTemporarySessionIfNeeded( reader
);
395 if ( reader
.isExtraLazy
) {
396 return reader
.element
;
404 protected int getCachedSize() {
408 private boolean isConnectedToSession() {
409 return session
!= null &&
411 session
.getPersistenceContext().containsCollection( this );
415 * Called by any writer method of the collection interface
417 protected final void write() {
423 * Is this collection in a state that would allow us to
424 * "queue" operations?
426 @SuppressWarnings({"JavaDoc"})
427 protected boolean isOperationQueueEnabled() {
428 return !initialized
&&
429 isConnectedToSession() &&
430 isInverseCollection();
434 * Is this collection in a state that would allow us to
435 * "queue" puts? This is a special case, because of orphan
438 @SuppressWarnings({"JavaDoc"})
439 protected boolean isPutQueueEnabled() {
440 return !initialized
&&
441 isConnectedToSession() &&
442 isInverseOneToManyOrNoOrphanDelete();
446 * Is this collection in a state that would allow us to
447 * "queue" clear? This is a special case, because of orphan
450 @SuppressWarnings({"JavaDoc"})
451 protected boolean isClearQueueEnabled() {
452 return !initialized
&&
453 isConnectedToSession() &&
454 isInverseCollectionNoOrphanDelete();
458 * Is this the "inverse" end of a bidirectional association?
460 @SuppressWarnings({"JavaDoc"})
461 private boolean isInverseCollection() {
462 CollectionEntry ce
= session
.getPersistenceContext().getCollectionEntry( this );
463 return ce
!= null && ce
.getLoadedPersister().isInverse();
467 * Is this the "inverse" end of a bidirectional association with
468 * no orphan delete enabled?
470 @SuppressWarnings({"JavaDoc"})
471 private boolean isInverseCollectionNoOrphanDelete() {
472 CollectionEntry ce
= session
.getPersistenceContext().getCollectionEntry( this );
474 ce
.getLoadedPersister().isInverse() &&
475 !ce
.getLoadedPersister().hasOrphanDelete();
479 * Is this the "inverse" end of a bidirectional one-to-many, or
480 * of a collection with no orphan delete?
482 @SuppressWarnings({"JavaDoc"})
483 private boolean isInverseOneToManyOrNoOrphanDelete() {
484 CollectionEntry ce
= session
.getPersistenceContext().getCollectionEntry( this );
485 return ce
!= null && ce
.getLoadedPersister().isInverse() && (
486 ce
.getLoadedPersister().isOneToMany() ||
487 !ce
.getLoadedPersister().hasOrphanDelete()
494 @SuppressWarnings({"JavaDoc"})
495 protected final void queueOperation(DelayedOperation operation
) {
496 if ( operationQueue
== null ) {
497 operationQueue
= new ArrayList
<DelayedOperation
>( 10 );
499 operationQueue
.add( operation
);
500 dirty
= true; //needed so that we remove this collection from the second-level cache
504 * After reading all existing elements from the database,
505 * add the queued elements to the underlying collection.
507 protected final void performQueuedOperations() {
508 for ( DelayedOperation operation
: operationQueue
) {
514 * After flushing, re-init snapshot state.
517 public void setSnapshot(Serializable key
, String role
, Serializable snapshot
) {
520 this.storedSnapshot
= snapshot
;
524 * After flushing, clear any "queued" additions, since the
525 * database state is now synchronized with the memory state.
528 public void postAction() {
529 operationQueue
= null;
535 * Not called by Hibernate, but used by non-JDK serialization,
536 * eg. SOAP libraries.
538 public AbstractPersistentCollection() {
541 protected AbstractPersistentCollection(SessionImplementor session
) {
542 this.session
= session
;
546 * return the user-visible collection (or array) instance
549 public Object
getValue() {
554 * Called just before reading any rows from the JDBC result set
557 public void beginRead() {
558 // override on some subclasses
563 * Called after reading all rows from the JDBC result set
566 public boolean endRead() {
567 //override on some subclasses
568 return afterInitialize();
572 public boolean afterInitialize() {
574 //do this bit after setting initialized to true or it will recurse
575 if ( operationQueue
!= null ) {
576 performQueuedOperations();
577 operationQueue
= null;
587 * Initialize the collection, if possible, wrapping any exceptions
588 * in a runtime exception
590 * @param writing currently obsolete
592 * @throws LazyInitializationException if we cannot initialize
594 protected final void initialize(final boolean writing
) {
595 // In remoting we are sure that session is null
596 // both when using property paths and switching off conversations
597 if(session
== null && remoting
) {
606 withTemporarySessionIfNeeded(
607 new LazyInitializationWork
<Object
>() {
609 public Object
doWork() {
610 session
.initializeCollection( AbstractPersistentCollection
.this, writing
);
617 private void throwLazyInitializationExceptionIfNotConnected() {
618 if ( !isConnectedToSession() ) {
619 throwLazyInitializationException( "no session or session was closed" );
621 if ( !session
.isConnected() ) {
622 throwLazyInitializationException( "session is disconnected" );
626 private void throwLazyInitializationException(String message
) {
627 throw new LazyInitializationException(
628 "failed to lazily initialize a collection" +
629 (role
== null ?
"" : " of role: " + role
) +
634 protected final void setInitialized() {
635 this.initializing
= false;
636 this.initialized
= true;
639 protected final void setDirectlyAccessible(boolean directlyAccessible
) {
640 this.directlyAccessible
= directlyAccessible
;
644 * Could the application possibly have a direct reference to
645 * the underlying collection implementation?
648 public boolean isDirectlyAccessible() {
649 return directlyAccessible
;
653 * Disassociate this collection from the given session.
655 * @return true if this was currently associated with the given session
658 public final boolean unsetSession(SessionImplementor currentSession
) {
659 prepareForPossibleSpecialSpecjInitialization();
660 if ( currentSession
== this.session
) {
669 protected void prepareForPossibleSpecialSpecjInitialization() {
670 if ( session
!= null ) {
671 specjLazyLoad
= session
.getFactory().getSettings().isInitializeLazyStateOutsideTransactionsEnabled();
673 if ( specjLazyLoad
&& sessionFactoryUuid
== null ) {
675 sessionFactoryUuid
= (String
) session
.getFactory().getReference().get( "uuid" ).getContent();
677 catch (NamingException e
) {
678 //not much we can do if this fails...
686 * Associate the collection with the given session.
688 * @return false if the collection was already associated with the session
690 * @throws HibernateException if the collection was already associated
691 * with another open session
694 public final boolean setCurrentSession(SessionImplementor session
) throws HibernateException
{
695 if ( session
== this.session
) {
699 if ( isConnectedToSession() ) {
700 CollectionEntry ce
= session
.getPersistenceContext().getCollectionEntry( this );
702 throw new HibernateException(
703 "Illegal attempt to associate a collection with two open sessions"
707 throw new HibernateException(
708 "Illegal attempt to associate a collection with two open sessions: " +
709 MessageHelper
.collectionInfoString(
710 ce
.getLoadedPersister(), this,
711 ce
.getLoadedKey(), session
717 this.session
= session
;
724 * Do we need to completely recreate this collection when it changes?
727 public boolean needsRecreate(CollectionPersister persister
) {
732 * To be called internally by the session, forcing
733 * immediate initialization.
736 public final void forceInitialization() throws HibernateException
{
737 if ( !initialized
) {
738 if ( initializing
) {
739 throw new AssertionFailure( "force initialize loading collection" );
741 if ( session
== null ) {
742 throw new HibernateException( "collection is not associated with any session" );
744 if ( !session
.isConnected() ) {
745 throw new HibernateException( "disconnected session" );
747 session
.initializeCollection( this, false );
753 * Get the current snapshot from the session
755 @SuppressWarnings({"JavaDoc"})
756 protected final Serializable
getSnapshot() {
757 return session
.getPersistenceContext().getSnapshot( this );
761 * Is this instance initialized?
764 public final boolean wasInitialized() {
769 public boolean isRowUpdatePossible() {
774 * Does this instance have any "queued" additions?
777 public final boolean hasQueuedOperations() {
778 return operationQueue
!= null;
782 * Iterate the "queued" additions
785 public final Iterator
queuedAdditionIterator() {
786 if ( hasQueuedOperations() ) {
787 return new Iterator() {
791 public Object
next() {
792 return operationQueue
.get( i
++ ).getAddedInstance();
796 public boolean hasNext() {
797 return i
< operationQueue
.size();
801 public void remove() {
802 throw new UnsupportedOperationException();
807 return EmptyIterator
.INSTANCE
;
812 * Iterate the "queued" additions
815 @SuppressWarnings({"unchecked"})
816 public final Collection
getQueuedOrphans(String entityName
) {
817 if ( hasQueuedOperations() ) {
818 Collection additions
= new ArrayList( operationQueue
.size() );
819 Collection removals
= new ArrayList( operationQueue
.size() );
820 for ( DelayedOperation operation
: operationQueue
) {
821 additions
.add( operation
.getAddedInstance() );
822 removals
.add( operation
.getOrphan() );
824 return getOrphans( removals
, additions
, entityName
, session
);
827 return Collections
.EMPTY_LIST
;
832 * Called before inserting rows, to ensure that any surrogate keys
833 * are fully generated
836 public void preInsert(CollectionPersister persister
) throws HibernateException
{
840 * Called after inserting a row, to fetch the natively generated id
843 public void afterRowInsert(CollectionPersister persister
, Object entry
, int i
) throws HibernateException
{
847 * get all "orphaned" elements
850 public abstract Collection
getOrphans(Serializable snapshot
, String entityName
) throws HibernateException
;
853 * Get the current session
855 @SuppressWarnings({"JavaDoc"})
856 public final SessionImplementor
getSession() {
860 protected final class IteratorProxy
implements Iterator
{
861 protected final Iterator itr
;
863 public IteratorProxy(Iterator itr
) {
868 public boolean hasNext() {
869 return itr
.hasNext();
873 public Object
next() {
878 public void remove() {
885 protected final class ListIteratorProxy
implements ListIterator
{
886 protected final ListIterator itr
;
888 public ListIteratorProxy(ListIterator itr
) {
893 @SuppressWarnings({"unchecked"})
894 public void add(Object o
) {
900 public boolean hasNext() {
901 return itr
.hasNext();
905 public boolean hasPrevious() {
906 return itr
.hasPrevious();
910 public Object
next() {
915 public int nextIndex() {
916 return itr
.nextIndex();
920 public Object
previous() {
921 return itr
.previous();
925 public int previousIndex() {
926 return itr
.previousIndex();
930 public void remove() {
936 @SuppressWarnings({"unchecked"})
937 public void set(Object o
) {
944 protected class SetProxy
implements java
.util
.Set
{
945 protected final Collection set
;
947 public SetProxy(Collection set
) {
952 @SuppressWarnings({"unchecked"})
953 public boolean add(Object o
) {
959 @SuppressWarnings({"unchecked"})
960 public boolean addAll(Collection c
) {
962 return set
.addAll( c
);
966 public void clear() {
972 public boolean contains(Object o
) {
973 return set
.contains( o
);
977 public boolean containsAll(Collection c
) {
978 return set
.containsAll( c
);
982 public boolean isEmpty() {
983 return set
.isEmpty();
987 public Iterator
iterator() {
988 return new IteratorProxy( set
.iterator() );
992 public boolean remove(Object o
) {
994 return set
.remove( o
);
998 public boolean removeAll(Collection c
) {
1000 return set
.removeAll( c
);
1004 public boolean retainAll(Collection c
) {
1006 return set
.retainAll( c
);
1015 public Object
[] toArray() {
1016 return set
.toArray();
1020 @SuppressWarnings({"unchecked"})
1021 public Object
[] toArray(Object
[] array
) {
1022 return set
.toArray( array
);
1027 protected final class ListProxy
implements java
.util
.List
{
1028 protected final List list
;
1030 public ListProxy(List list
) {
1035 @SuppressWarnings({"unchecked"})
1036 public void add(int index
, Object value
) {
1038 list
.add( index
, value
);
1042 @SuppressWarnings({"unchecked"})
1043 public boolean add(Object o
) {
1045 return list
.add( o
);
1049 @SuppressWarnings({"unchecked"})
1050 public boolean addAll(Collection c
) {
1052 return list
.addAll( c
);
1056 @SuppressWarnings({"unchecked"})
1057 public boolean addAll(int i
, Collection c
) {
1059 return list
.addAll( i
, c
);
1063 public void clear() {
1069 public boolean contains(Object o
) {
1070 return list
.contains( o
);
1074 public boolean containsAll(Collection c
) {
1075 return list
.containsAll( c
);
1079 public Object
get(int i
) {
1080 return list
.get( i
);
1084 public int indexOf(Object o
) {
1085 return list
.indexOf( o
);
1089 public boolean isEmpty() {
1090 return list
.isEmpty();
1094 public Iterator
iterator() {
1095 return new IteratorProxy( list
.iterator() );
1099 public int lastIndexOf(Object o
) {
1100 return list
.lastIndexOf( o
);
1104 public ListIterator
listIterator() {
1105 return new ListIteratorProxy( list
.listIterator() );
1109 public ListIterator
listIterator(int i
) {
1110 return new ListIteratorProxy( list
.listIterator( i
) );
1114 public Object
remove(int i
) {
1116 return list
.remove( i
);
1120 public boolean remove(Object o
) {
1122 return list
.remove( o
);
1126 public boolean removeAll(Collection c
) {
1128 return list
.removeAll( c
);
1132 public boolean retainAll(Collection c
) {
1134 return list
.retainAll( c
);
1138 @SuppressWarnings({"unchecked"})
1139 public Object
set(int i
, Object o
) {
1141 return list
.set( i
, o
);
1150 public List
subList(int i
, int j
) {
1151 return list
.subList( i
, j
);
1155 public Object
[] toArray() {
1156 return list
.toArray();
1160 @SuppressWarnings({"unchecked"})
1161 public Object
[] toArray(Object
[] array
) {
1162 return list
.toArray( array
);
1168 * Contract for operations which are part of a collection's operation queue.
1170 protected interface DelayedOperation
{
1171 public void operate();
1173 public Object
getAddedInstance();
1175 public Object
getOrphan();
1179 * Given a collection of entity instances that used to
1180 * belong to the collection, and a collection of instances
1181 * that currently belong, return a collection of orphans
1183 @SuppressWarnings({"JavaDoc", "unchecked"})
1184 protected static Collection
getOrphans(
1185 Collection oldElements
,
1186 Collection currentElements
,
1188 SessionImplementor session
) throws HibernateException
{
1191 if ( currentElements
.size() == 0 ) {
1192 return oldElements
; // no new elements, the old list contains only Orphans
1194 if ( oldElements
.size() == 0 ) {
1195 return oldElements
; // no old elements, so no Orphans neither
1198 final EntityPersister entityPersister
= session
.getFactory().getEntityPersister( entityName
);
1199 final Type idType
= entityPersister
.getIdentifierType();
1201 // create the collection holding the Orphans
1202 Collection res
= new ArrayList();
1204 // collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access
1205 java
.util
.Set currentIds
= new HashSet();
1206 java
.util
.Set currentSaving
= new IdentitySet();
1207 for ( Object current
: currentElements
) {
1208 if ( current
!= null && ForeignKeys
.isNotTransient( entityName
, current
, null, session
) ) {
1209 EntityEntry ee
= session
.getPersistenceContext().getEntry( current
);
1210 if ( ee
!= null && ee
.getStatus() == Status
.SAVING
) {
1211 currentSaving
.add( current
);
1214 Serializable currentId
= ForeignKeys
.getEntityIdentifierIfNotUnsaved(
1219 currentIds
.add( new TypedValue( idType
, currentId
, entityPersister
.getEntityMode() ) );
1224 // iterate over the *old* list
1225 for ( Object old
: oldElements
) {
1226 if ( !currentSaving
.contains( old
) ) {
1227 Serializable oldId
= ForeignKeys
.getEntityIdentifierIfNotUnsaved( entityName
, old
, session
);
1228 if ( !currentIds
.contains( new TypedValue( idType
, oldId
, entityPersister
.getEntityMode() ) ) ) {
1237 public static void identityRemove(
1241 SessionImplementor session
) throws HibernateException
{
1243 if ( object
!= null && ForeignKeys
.isNotTransient( entityName
, object
, null, session
) ) {
1244 final EntityPersister entityPersister
= session
.getFactory().getEntityPersister( entityName
);
1245 Type idType
= entityPersister
.getIdentifierType();
1247 Serializable idOfCurrent
= ForeignKeys
.getEntityIdentifierIfNotUnsaved( entityName
, object
, session
);
1248 Iterator itr
= list
.iterator();
1249 while ( itr
.hasNext() ) {
1250 Serializable idOfOld
= ForeignKeys
.getEntityIdentifierIfNotUnsaved( entityName
, itr
.next(), session
);
1251 if ( idType
.isEqual( idOfCurrent
, idOfOld
, session
.getFactory() ) ) {
1261 public Object
getIdentifier(Object entry
, int i
) {
1262 throw new UnsupportedOperationException();
1266 public Object
getOwner() {
1271 public void setOwner(Object owner
) {
1275 /** ------ Below is section of code which makes remote service calls ----- */
1276 // The affected methods are :
1277 // initialize(final boolean writing)
1279 // readIndexExistence(final Object index)
1280 // readElementExistence(final Object element)
1281 // readElementByIndex(final Object index)
1283 private static CdmApplicationRemoteConfiguration configuration
;
1284 private static boolean remoting
= false;
1286 public static void setConfiguration(CdmApplicationRemoteConfiguration conf
) {
1288 configuration
= conf
;
1292 private void remoteInitialize() {
1294 if (getOwner() != null && !initialized
) {
1297 String role
= getRole();
1298 String fieldName
= role
.substring(role
.lastIndexOf(".") + 1);
1299 log
.info("--> Remote Lazy Initializing Collection " + getRole() + " , key : " + getKey() + " , field : " + fieldName
);
1300 Object owner
= getOwner();
1302 if(configuration
== null) {
1303 throw new HibernateException("CdmApplicationRemoteConfiguration not initialized (null)");
1305 ICachedCommonService cachedCommonService
= configuration
.getCachedCommonService();
1306 if(cachedCommonService
== null) {
1307 throw new HibernateException("commonService not initialized (null)");
1310 PersistentCollection col
= cachedCommonService
.initializeCollection(this);
1313 Class
<?
> clazz
= getClass();
1314 if (clazz
!= null) {
1315 CollectionField cf
= cachedCommonService
.getCollectionField(col
);
1316 cachedCommonService
.updatePersistentCollection(cf
);
1317 Field field
= clazz
.getDeclaredField(cf
.getType().toString());
1318 field
.setAccessible(true);
1319 field
.set(this, cf
.getCollection());
1321 } catch (Exception ex
) {
1322 throw new CdmEagerLoadingException(ex
);