Search in sources :

Example 11 with EntityKey

use of org.hibernate.engine.spi.EntityKey in project hibernate-orm by hibernate.

the class DefaultLoadEventListener method assembleCacheEntry.

private Object assembleCacheEntry(final StandardCacheEntryImpl entry, final Serializable id, final EntityPersister persister, final LoadEvent event) throws HibernateException {
    final Object optionalObject = event.getInstanceToLoad();
    final EventSource session = event.getSession();
    final SessionFactoryImplementor factory = session.getFactory();
    if (traceEnabled) {
        LOG.tracev("Assembling entity from second-level cache: {0}", MessageHelper.infoString(persister, id, factory));
    }
    EntityPersister subclassPersister = factory.getEntityPersister(entry.getSubclass());
    Object result = optionalObject == null ? session.instantiate(subclassPersister, id) : optionalObject;
    // make it circular-reference safe
    final EntityKey entityKey = session.generateEntityKey(id, subclassPersister);
    TwoPhaseLoad.addUninitializedCachedEntity(entityKey, result, subclassPersister, LockMode.NONE, entry.getVersion(), session);
    Type[] types = subclassPersister.getPropertyTypes();
    Object[] values = entry.assemble(result, id, subclassPersister, session.getInterceptor(), session);
    // intializes result by side-effect
    TypeHelper.deepCopy(values, types, subclassPersister.getPropertyUpdateability(), values, session);
    Object version = Versioning.getVersion(values, subclassPersister);
    LOG.tracev("Cached Version: {0}", version);
    final PersistenceContext persistenceContext = session.getPersistenceContext();
    boolean isReadOnly = session.isDefaultReadOnly();
    if (persister.isMutable()) {
        Object proxy = persistenceContext.getProxy(entityKey);
        if (proxy != null) {
            // there is already a proxy for this impl
            // only set the status to read-only if the proxy is read-only
            isReadOnly = ((HibernateProxy) proxy).getHibernateLazyInitializer().isReadOnly();
        }
    } else {
        isReadOnly = true;
    }
    persistenceContext.addEntry(result, (isReadOnly ? Status.READ_ONLY : Status.MANAGED), values, null, id, version, LockMode.NONE, true, subclassPersister, false);
    subclassPersister.afterInitialize(result, session);
    persistenceContext.initializeNonLazyCollections();
    // upgrade the lock if necessary:
    //lock(result, lockMode);
    //PostLoad is needed for EJB3
    //TODO: reuse the PostLoadEvent...
    PostLoadEvent postLoadEvent = event.getPostLoadEvent().setEntity(result).setId(id).setPersister(persister);
    for (PostLoadEventListener listener : postLoadEventListeners(session)) {
        listener.onPostLoad(postLoadEvent);
    }
    return result;
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) PostLoadEvent(org.hibernate.event.spi.PostLoadEvent) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) StatefulPersistenceContext(org.hibernate.engine.internal.StatefulPersistenceContext) HibernateProxy(org.hibernate.proxy.HibernateProxy) PostLoadEventListener(org.hibernate.event.spi.PostLoadEventListener) EntityKey(org.hibernate.engine.spi.EntityKey) EventSource(org.hibernate.event.spi.EventSource) EmbeddedComponentType(org.hibernate.type.EmbeddedComponentType) EntityType(org.hibernate.type.EntityType) EventType(org.hibernate.event.spi.EventType) Type(org.hibernate.type.Type)

Example 12 with EntityKey

use of org.hibernate.engine.spi.EntityKey in project hibernate-orm by hibernate.

the class Loader method registerNonExists.

/**
	 * For missing objects associated by one-to-one with another object in the
	 * result set, register the fact that the the object is missing with the
	 * session.
	 */
private void registerNonExists(final EntityKey[] keys, final Loadable[] persisters, final SharedSessionContractImplementor session) {
    final int[] owners = getOwners();
    if (owners != null) {
        EntityType[] ownerAssociationTypes = getOwnerAssociationTypes();
        for (int i = 0; i < keys.length; i++) {
            int owner = owners[i];
            if (owner > -1) {
                EntityKey ownerKey = keys[owner];
                if (keys[i] == null && ownerKey != null) {
                    final PersistenceContext persistenceContext = session.getPersistenceContext();
                    /*final boolean isPrimaryKey;
						final boolean isSpecialOneToOne;
						if ( ownerAssociationTypes == null || ownerAssociationTypes[i] == null ) {
							isPrimaryKey = true;
							isSpecialOneToOne = false;
						}
						else {
							isPrimaryKey = ownerAssociationTypes[i].getRHSUniqueKeyPropertyName()==null;
							isSpecialOneToOne = ownerAssociationTypes[i].getLHSPropertyName()!=null;
						}*/
                    //TODO: can we *always* use the "null property" approach for everything?
                    /*if ( isPrimaryKey && !isSpecialOneToOne ) {
							persistenceContext.addNonExistantEntityKey(
									new EntityKey( ownerKey.getIdentifier(), persisters[i], session.getEntityMode() )
							);
						}
						else if ( isSpecialOneToOne ) {*/
                    boolean isOneToOneAssociation = ownerAssociationTypes != null && ownerAssociationTypes[i] != null && ownerAssociationTypes[i].isOneToOne();
                    if (isOneToOneAssociation) {
                        persistenceContext.addNullProperty(ownerKey, ownerAssociationTypes[i].getPropertyName());
                    }
                /*}
						else {
							persistenceContext.addNonExistantEntityUniqueKey( new EntityUniqueKey(
									persisters[i].getEntityName(),
									ownerAssociationTypes[i].getRHSUniqueKeyPropertyName(),
									ownerKey.getIdentifier(),
									persisters[owner].getIdentifierType(),
									session.getEntityMode()
							) );
						}*/
                }
            }
        }
    }
}
Also used : EntityType(org.hibernate.type.EntityType) EntityKey(org.hibernate.engine.spi.EntityKey) PersistenceContext(org.hibernate.engine.spi.PersistenceContext)

Example 13 with EntityKey

use of org.hibernate.engine.spi.EntityKey in project hibernate-orm by hibernate.

the class DynamicBatchingEntityLoaderBuilder method performOrderedMultiLoad.

@SuppressWarnings("unchecked")
private List performOrderedMultiLoad(OuterJoinLoadable persister, Serializable[] ids, SharedSessionContractImplementor session, MultiLoadOptions loadOptions) {
    assert loadOptions.isOrderReturnEnabled();
    final List result = CollectionHelper.arrayList(ids.length);
    final LockOptions lockOptions = (loadOptions.getLockOptions() == null) ? new LockOptions(LockMode.NONE) : loadOptions.getLockOptions();
    final int maxBatchSize;
    if (loadOptions.getBatchSize() != null && loadOptions.getBatchSize() > 0) {
        maxBatchSize = loadOptions.getBatchSize();
    } else {
        maxBatchSize = session.getJdbcServices().getJdbcEnvironment().getDialect().getDefaultBatchLoadSizingStrategy().determineOptimalBatchLoadSize(persister.getIdentifierType().getColumnSpan(session.getFactory()), ids.length);
    }
    final List<Serializable> idsInBatch = new ArrayList<>();
    final List<Integer> elementPositionsLoadedByBatch = new ArrayList<>();
    for (int i = 0; i < ids.length; i++) {
        final Serializable id = ids[i];
        final EntityKey entityKey = new EntityKey(id, persister);
        if (loadOptions.isSessionCheckingEnabled()) {
            // look for it in the Session first
            final Object managedEntity = session.getPersistenceContext().getEntity(entityKey);
            if (managedEntity != null) {
                if (!loadOptions.isReturnOfDeletedEntitiesEnabled()) {
                    final EntityEntry entry = session.getPersistenceContext().getEntry(managedEntity);
                    if (entry.getStatus() == Status.DELETED || entry.getStatus() == Status.GONE) {
                        // put a null in the result
                        result.add(i, null);
                        continue;
                    }
                }
                // if we did not hit the continue above, there is already an
                // entry in the PC for that entity, so use it...
                result.add(i, managedEntity);
                continue;
            }
        }
        // if we did not hit any of the continues above, then we need to batch
        // load the entity state.
        idsInBatch.add(ids[i]);
        if (idsInBatch.size() >= maxBatchSize) {
            performOrderedBatchLoad(idsInBatch, lockOptions, persister, session);
        }
        // Save the EntityKey instance for use later!
        result.add(i, entityKey);
        elementPositionsLoadedByBatch.add(i);
    }
    if (!idsInBatch.isEmpty()) {
        performOrderedBatchLoad(idsInBatch, lockOptions, persister, session);
    }
    for (Integer position : elementPositionsLoadedByBatch) {
        // the element value at this position in the result List should be
        // the EntityKey for that entity; reuse it!
        final EntityKey entityKey = (EntityKey) result.get(position);
        Object entity = session.getPersistenceContext().getEntity(entityKey);
        if (entity != null && !loadOptions.isReturnOfDeletedEntitiesEnabled()) {
            // make sure it is not DELETED
            final EntityEntry entry = session.getPersistenceContext().getEntry(entity);
            if (entry.getStatus() == Status.DELETED || entry.getStatus() == Status.GONE) {
                // the entity is locally deleted, and the options ask that we not return such entities...
                entity = null;
            }
        }
        result.set(position, entity);
    }
    return result;
}
Also used : EntityKey(org.hibernate.engine.spi.EntityKey) Serializable(java.io.Serializable) EntityEntry(org.hibernate.engine.spi.EntityEntry) LockOptions(org.hibernate.LockOptions) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 14 with EntityKey

use of org.hibernate.engine.spi.EntityKey in project hibernate-orm by hibernate.

the class Loader method processResultSet.

protected List processResultSet(ResultSet rs, QueryParameters queryParameters, SharedSessionContractImplementor session, boolean returnProxies, ResultTransformer forcedResultTransformer, int maxRows, List<AfterLoadAction> afterLoadActions) throws SQLException {
    final int entitySpan = getEntityPersisters().length;
    final EntityKey optionalObjectKey = getOptionalObjectKey(queryParameters, session);
    final LockMode[] lockModesArray = getLockModes(queryParameters.getLockOptions());
    final boolean createSubselects = isSubselectLoadingEnabled();
    final List subselectResultKeys = createSubselects ? new ArrayList() : null;
    final ArrayList hydratedObjects = entitySpan == 0 ? null : new ArrayList(entitySpan * 10);
    final List results = new ArrayList();
    handleEmptyCollections(queryParameters.getCollectionKeys(), rs, session);
    //we can reuse it for each row
    EntityKey[] keys = new EntityKey[entitySpan];
    LOG.trace("Processing result set");
    int count;
    for (count = 0; count < maxRows && rs.next(); count++) {
        if (DEBUG_ENABLED) {
            LOG.debugf("Result set row: %s", count);
        }
        Object result = getRowFromResultSet(rs, session, queryParameters, lockModesArray, optionalObjectKey, hydratedObjects, keys, returnProxies, forcedResultTransformer);
        results.add(result);
        if (createSubselects) {
            subselectResultKeys.add(keys);
            //can't reuse in this case
            keys = new EntityKey[entitySpan];
        }
    }
    LOG.tracev("Done processing result set ({0} rows)", count);
    initializeEntitiesAndCollections(hydratedObjects, rs, session, queryParameters.isReadOnly(session), afterLoadActions);
    if (createSubselects) {
        createSubselects(subselectResultKeys, queryParameters, session);
    }
    return results;
}
Also used : EntityKey(org.hibernate.engine.spi.EntityKey) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) LockMode(org.hibernate.LockMode)

Example 15 with EntityKey

use of org.hibernate.engine.spi.EntityKey in project hibernate-orm by hibernate.

the class AbstractCollectionPersister method getSubselectInitializer.

private CollectionInitializer getSubselectInitializer(Serializable key, SharedSessionContractImplementor session) {
    if (!isSubselectLoadable()) {
        return null;
    }
    final PersistenceContext persistenceContext = session.getPersistenceContext();
    SubselectFetch subselect = persistenceContext.getBatchFetchQueue().getSubselect(session.generateEntityKey(key, getOwnerEntityPersister()));
    if (subselect == null) {
        return null;
    } else {
        // Take care of any entities that might have
        // been evicted!
        Iterator iter = subselect.getResult().iterator();
        while (iter.hasNext()) {
            if (!persistenceContext.containsEntity((EntityKey) iter.next())) {
                iter.remove();
            }
        }
        // Run a subquery loader
        return createSubselectInitializer(subselect, session);
    }
}
Also used : EntityKey(org.hibernate.engine.spi.EntityKey) SubselectFetch(org.hibernate.engine.spi.SubselectFetch) Iterator(java.util.Iterator) PersistenceContext(org.hibernate.engine.spi.PersistenceContext)

Aggregations

EntityKey (org.hibernate.engine.spi.EntityKey)43 Serializable (java.io.Serializable)13 EntityEntry (org.hibernate.engine.spi.EntityEntry)12 EntityPersister (org.hibernate.persister.entity.EntityPersister)10 EventSource (org.hibernate.event.spi.EventSource)8 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)7 List (java.util.List)6 EntityType (org.hibernate.type.EntityType)6 ArrayList (java.util.ArrayList)5 SQLException (java.sql.SQLException)4 EntityReferenceProcessingState (org.hibernate.loader.plan.exec.process.spi.ResultSetProcessingContext.EntityReferenceProcessingState)4 ResultSet (java.sql.ResultSet)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 HibernateException (org.hibernate.HibernateException)3 CollectionEntry (org.hibernate.engine.spi.CollectionEntry)3 SubselectFetch (org.hibernate.engine.spi.SubselectFetch)3 HibernateProxy (org.hibernate.proxy.HibernateProxy)3 Type (org.hibernate.type.Type)3 HashSet (java.util.HashSet)2