Search in sources :

Example 36 with CollectionPersister

use of org.hibernate.persister.collection.CollectionPersister in project hibernate-orm by hibernate.

the class Loader method initializeEntitiesAndCollections.

private void initializeEntitiesAndCollections(final List hydratedObjects, final Object resultSetId, final SharedSessionContractImplementor session, final boolean readOnly, List<AfterLoadAction> afterLoadActions) throws HibernateException {
    final CollectionPersister[] collectionPersisters = getCollectionPersisters();
    if (collectionPersisters != null) {
        for (CollectionPersister collectionPersister : collectionPersisters) {
            if (collectionPersister.isArray()) {
                //for arrays, we should end the collection load beforeQuery resolving
                //the entities, since the actual array instances are not instantiated
                //during loading
                //TODO: or we could do this polymorphically, and have two
                //      different operations implemented differently for arrays
                endCollectionLoad(resultSetId, session, collectionPersister);
            }
        }
    }
    //important: reuse the same event instances for performance!
    final PreLoadEvent pre;
    final PostLoadEvent post;
    if (session.isEventSource()) {
        pre = new PreLoadEvent((EventSource) session);
        post = new PostLoadEvent((EventSource) session);
    } else {
        pre = null;
        post = null;
    }
    if (hydratedObjects != null) {
        int hydratedObjectsSize = hydratedObjects.size();
        LOG.tracev("Total objects hydrated: {0}", hydratedObjectsSize);
        for (Object hydratedObject : hydratedObjects) {
            TwoPhaseLoad.initializeEntity(hydratedObject, readOnly, session, pre);
        }
    }
    if (collectionPersisters != null) {
        for (CollectionPersister collectionPersister : collectionPersisters) {
            if (!collectionPersister.isArray()) {
                //for sets, we should end the collection load afterQuery resolving
                //the entities, since we might call hashCode() on the elements
                //TODO: or we could do this polymorphically, and have two
                //      different operations implemented differently for arrays
                endCollectionLoad(resultSetId, session, collectionPersister);
            }
        }
    }
    // persistence context.
    if (hydratedObjects != null) {
        for (Object hydratedObject : hydratedObjects) {
            TwoPhaseLoad.postLoad(hydratedObject, session, post);
            if (afterLoadActions != null) {
                for (AfterLoadAction afterLoadAction : afterLoadActions) {
                    final EntityEntry entityEntry = session.getPersistenceContext().getEntry(hydratedObject);
                    if (entityEntry == null) {
                        // big problem
                        throw new HibernateException("Could not locate EntityEntry immediately afterQuery two-phase load");
                    }
                    afterLoadAction.afterLoad(session, hydratedObject, (Loadable) entityEntry.getPersister());
                }
            }
        }
    }
}
Also used : PostLoadEvent(org.hibernate.event.spi.PostLoadEvent) EventSource(org.hibernate.event.spi.EventSource) EntityEntry(org.hibernate.engine.spi.EntityEntry) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) HibernateException(org.hibernate.HibernateException) AfterLoadAction(org.hibernate.loader.spi.AfterLoadAction) PreLoadEvent(org.hibernate.event.spi.PreLoadEvent)

Example 37 with CollectionPersister

use of org.hibernate.persister.collection.CollectionPersister in project hibernate-orm by hibernate.

the class Loader method handleEmptyCollections.

/**
	 * If this is a collection initializer, we need to tell the session that a collection
	 * is being initialized, to account for the possibility of the collection having
	 * no elements (hence no rows in the result set).
	 */
private void handleEmptyCollections(final Serializable[] keys, final Object resultSetId, final SharedSessionContractImplementor session) {
    if (keys != null) {
        final boolean debugEnabled = LOG.isDebugEnabled();
        // this is a collection initializer, so we must create a collection
        // for each of the passed-in keys, to account for the possibility
        // that the collection is empty and has no rows in the result set
        CollectionPersister[] collectionPersisters = getCollectionPersisters();
        for (CollectionPersister collectionPersister : collectionPersisters) {
            for (Serializable key : keys) {
                //handle empty collections
                if (debugEnabled) {
                    LOG.debugf("Result set contains (possibly empty) collection: %s", MessageHelper.collectionInfoString(collectionPersister, key, getFactory()));
                }
                session.getPersistenceContext().getLoadContexts().getCollectionLoadContext((ResultSet) resultSetId).getLoadingCollection(collectionPersister, key);
            }
        }
    }
// else this is not a collection initializer (and empty collections will
// be detected by looking for the owner's identifier in the result set)
}
Also used : Serializable(java.io.Serializable) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) ResultSet(java.sql.ResultSet)

Example 38 with CollectionPersister

use of org.hibernate.persister.collection.CollectionPersister in project hibernate-orm by hibernate.

the class Loader method readCollectionElements.

/**
	 * Read any collection elements contained in a single row of the result set
	 */
private void readCollectionElements(Object[] row, ResultSet resultSet, SharedSessionContractImplementor session) throws SQLException, HibernateException {
    //TODO: make this handle multiple collection roles!
    final CollectionPersister[] collectionPersisters = getCollectionPersisters();
    if (collectionPersisters != null) {
        final CollectionAliases[] descriptors = getCollectionAliases();
        final int[] collectionOwners = getCollectionOwners();
        for (int i = 0; i < collectionPersisters.length; i++) {
            final boolean hasCollectionOwners = collectionOwners != null && collectionOwners[i] > -1;
            //true if this is a query and we are loading multiple instances of the same collection role
            //otherwise this is a CollectionInitializer and we are loading up a single collection or batch
            final Object owner = hasCollectionOwners ? row[collectionOwners[i]] : //if null, owner will be retrieved from session
            null;
            final CollectionPersister collectionPersister = collectionPersisters[i];
            final Serializable key;
            if (owner == null) {
                key = null;
            } else {
                key = collectionPersister.getCollectionType().getKeyOfOwner(owner, session);
            //TODO: old version did not require hashmap lookup:
            //keys[collectionOwner].getIdentifier()
            }
            readCollectionElement(owner, key, collectionPersister, descriptors[i], resultSet, session);
        }
    }
}
Also used : Serializable(java.io.Serializable) CollectionPersister(org.hibernate.persister.collection.CollectionPersister)

Example 39 with CollectionPersister

use of org.hibernate.persister.collection.CollectionPersister in project hibernate-orm by hibernate.

the class JoinWalker method initPersisters.

protected void initPersisters(final List associations, final LockOptions lockOptions, final AssociationInitCallback callback) throws MappingException {
    final int joins = countEntityPersisters(associations);
    final int collections = countCollectionPersisters(associations);
    collectionOwners = collections == 0 ? null : new int[collections];
    collectionPersisters = collections == 0 ? null : new CollectionPersister[collections];
    collectionSuffixes = BasicLoader.generateSuffixes(joins + 1, collections);
    this.lockOptions = lockOptions;
    persisters = new Loadable[joins];
    aliases = new String[joins];
    owners = new int[joins];
    ownerAssociationTypes = new EntityType[joins];
    lockModeArray = ArrayHelper.fillArray(lockOptions.getLockMode(), joins);
    int i = 0;
    int j = 0;
    for (Object association : associations) {
        final OuterJoinableAssociation oj = (OuterJoinableAssociation) association;
        if (!oj.isCollection()) {
            persisters[i] = (Loadable) oj.getJoinable();
            aliases[i] = oj.getRHSAlias();
            owners[i] = oj.getOwner(associations);
            ownerAssociationTypes[i] = (EntityType) oj.getJoinableType();
            callback.associationProcessed(oj, i);
            i++;
        } else {
            QueryableCollection collPersister = (QueryableCollection) oj.getJoinable();
            if (oj.getJoinType() == JoinType.LEFT_OUTER_JOIN && !oj.hasRestriction()) {
                //it must be a collection fetch
                collectionPersisters[j] = collPersister;
                collectionOwners[j] = oj.getOwner(associations);
                j++;
            }
            if (collPersister.isOneToMany()) {
                persisters[i] = (Loadable) collPersister.getElementPersister();
                aliases[i] = oj.getRHSAlias();
                callback.associationProcessed(oj, i);
                i++;
            }
        }
    }
    if (ArrayHelper.isAllNegative(owners)) {
        owners = null;
    }
    if (collectionOwners != null && ArrayHelper.isAllNegative(collectionOwners)) {
        collectionOwners = null;
    }
}
Also used : CollectionPersister(org.hibernate.persister.collection.CollectionPersister) QueryableCollection(org.hibernate.persister.collection.QueryableCollection)

Example 40 with CollectionPersister

use of org.hibernate.persister.collection.CollectionPersister in project hibernate-orm by hibernate.

the class CollectionUpdateAction method execute.

@Override
public void execute() throws HibernateException {
    final Serializable id = getKey();
    final SharedSessionContractImplementor session = getSession();
    final CollectionPersister persister = getPersister();
    final PersistentCollection collection = getCollection();
    final boolean affectedByFilters = persister.isAffectedByEnabledFilters(session);
    preUpdate();
    if (!collection.wasInitialized()) {
        if (!collection.hasQueuedOperations()) {
            throw new AssertionFailure("no queued adds");
        }
    //do nothing - we only need to notify the cache... 
    } else if (!affectedByFilters && collection.empty()) {
        if (!emptySnapshot) {
            persister.remove(id, session);
        }
    } else if (collection.needsRecreate(persister)) {
        if (affectedByFilters) {
            throw new HibernateException("cannot recreate collection while filter is enabled: " + MessageHelper.collectionInfoString(persister, collection, id, session));
        }
        if (!emptySnapshot) {
            persister.remove(id, session);
        }
        persister.recreate(collection, id, session);
    } else {
        persister.deleteRows(collection, id, session);
        persister.updateRows(collection, id, session);
        persister.insertRows(collection, id, session);
    }
    getSession().getPersistenceContext().getCollectionEntry(collection).afterAction(collection);
    evict();
    postUpdate();
    if (getSession().getFactory().getStatistics().isStatisticsEnabled()) {
        getSession().getFactory().getStatistics().updateCollection(getPersister().getRole());
    }
}
Also used : PersistentCollection(org.hibernate.collection.spi.PersistentCollection) Serializable(java.io.Serializable) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) AssertionFailure(org.hibernate.AssertionFailure) HibernateException(org.hibernate.HibernateException) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor)

Aggregations

CollectionPersister (org.hibernate.persister.collection.CollectionPersister)44 HibernateException (org.hibernate.HibernateException)11 Type (org.hibernate.type.Type)9 PersistentCollection (org.hibernate.collection.spi.PersistentCollection)8 Serializable (java.io.Serializable)7 CollectionRegionAccessStrategy (org.hibernate.cache.spi.access.CollectionRegionAccessStrategy)7 CollectionType (org.hibernate.type.CollectionType)7 HashMap (java.util.HashMap)6 Session (org.hibernate.Session)6 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)6 EntityPersister (org.hibernate.persister.entity.EntityPersister)6 Test (org.junit.Test)6 Map (java.util.Map)5 CollectionEntry (org.hibernate.engine.spi.CollectionEntry)5 EntityEntry (org.hibernate.engine.spi.EntityEntry)5 CompositeType (org.hibernate.type.CompositeType)5 EntityType (org.hibernate.type.EntityType)5 ResultSet (java.sql.ResultSet)4 AssertionFailure (org.hibernate.AssertionFailure)4 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)4