Search in sources :

Example 11 with EntityMode

use of org.hibernate.EntityMode in project hibernate-orm by hibernate.

the class CollectionLoadContext method getLoadingCollection.

/**
 * Retrieve the collection that is being loaded as part of processing this
 * result set.
 * <p/>
 * Basically, there are two valid return values from this method:<ul>
 * <li>an instance of {@link org.hibernate.collection.spi.PersistentCollection} which indicates to
 * continue loading the result set row data into that returned collection
 * instance; this may be either an instance already associated and in the
 * midst of being loaded, or a newly instantiated instance as a matching
 * associated collection was not found.</li>
 * <li><i>null</i> indicates to ignore the corresponding result set row
 * data relating to the requested collection; this indicates that either
 * the collection was found to already be associated with the persistence
 * context in a fully loaded state, or it was found in a loading state
 * associated with another result set processing context.</li>
 * </ul>
 *
 * @param persister The persister for the collection being requested.
 * @param key The key of the collection being requested.
 *
 * @return The loading collection (see discussion above).
 */
public PersistentCollection getLoadingCollection(final CollectionPersister persister, final Serializable key) {
    final EntityMode em = persister.getOwnerEntityPersister().getEntityMetamodel().getEntityMode();
    final CollectionKey collectionKey = new CollectionKey(persister, key, em);
    if (LOG.isTraceEnabled()) {
        LOG.tracev("Starting attempt to find loading collection [{0}]", MessageHelper.collectionInfoString(persister.getRole(), key));
    }
    final LoadingCollectionEntry loadingCollectionEntry = loadContexts.locateLoadingCollectionEntry(collectionKey);
    if (loadingCollectionEntry == null) {
        // look for existing collection as part of the persistence context
        PersistentCollection collection = loadContexts.getPersistenceContext().getCollection(collectionKey);
        if (collection != null) {
            if (collection.wasInitialized()) {
                LOG.trace("Collection already initialized; ignoring");
                // ignore this row of results! Note the early exit
                return null;
            }
            LOG.trace("Collection not yet initialized; initializing");
        } else {
            final Object owner = loadContexts.getPersistenceContext().getCollectionOwner(key, persister);
            final boolean newlySavedEntity = owner != null && loadContexts.getPersistenceContext().getEntry(owner).getStatus() != Status.LOADING;
            if (newlySavedEntity) {
                // important, to account for newly saved entities in query
                // todo : some kind of check for new status...
                LOG.trace("Owning entity already loaded; ignoring");
                return null;
            }
            // create one
            LOG.tracev("Instantiating new collection [key={0}, rs={1}]", key, resultSet);
            collection = persister.getCollectionType().instantiate(loadContexts.getPersistenceContext().getSession(), persister, key);
        }
        collection.beforeInitialize(persister, -1);
        collection.beginRead();
        localLoadingCollectionKeys.add(collectionKey);
        loadContexts.registerLoadingCollectionXRef(collectionKey, new LoadingCollectionEntry(resultSet, persister, key, collection));
        return collection;
    }
    if (loadingCollectionEntry.getResultSet() == resultSet) {
        LOG.trace("Found loading collection bound to current result set processing; reading row");
        return loadingCollectionEntry.getCollection();
    }
    // ignore this row, the collection is in process of
    // being loaded somewhere further "up" the stack
    LOG.trace("Collection is already being initialized; ignoring row");
    return null;
}
Also used : PersistentCollection(org.hibernate.collection.spi.PersistentCollection) CollectionKey(org.hibernate.engine.spi.CollectionKey) EntityMode(org.hibernate.EntityMode)

Example 12 with EntityMode

use of org.hibernate.EntityMode in project hibernate-orm by hibernate.

the class EntityBinder method bindEntity.

public void bindEntity() {
    persistentClass.setAbstract(annotatedClass.isAbstract());
    persistentClass.setClassName(annotatedClass.getName());
    persistentClass.setJpaEntityName(name);
    // persistentClass.setDynamic(false); //no longer needed with the Entity name refactoring?
    persistentClass.setEntityName(annotatedClass.getName());
    bindDiscriminatorValue();
    persistentClass.setLazy(lazy);
    if (proxyClass != null) {
        persistentClass.setProxyInterfaceName(proxyClass.getName());
    }
    persistentClass.setDynamicInsert(dynamicInsert);
    persistentClass.setDynamicUpdate(dynamicUpdate);
    if (persistentClass instanceof RootClass) {
        RootClass rootClass = (RootClass) persistentClass;
        boolean mutable = true;
        // priority on @Immutable, then @Entity.mutable()
        if (annotatedClass.isAnnotationPresent(Immutable.class)) {
            mutable = false;
        } else {
            org.hibernate.annotations.Entity entityAnn = annotatedClass.getAnnotation(org.hibernate.annotations.Entity.class);
            if (entityAnn != null) {
                mutable = entityAnn.mutable();
            }
        }
        rootClass.setMutable(mutable);
        rootClass.setExplicitPolymorphism(isExplicitPolymorphism(polymorphismType));
        if (StringHelper.isNotEmpty(where)) {
            rootClass.setWhere(where);
        }
        if (cacheConcurrentStrategy != null) {
            rootClass.setCacheConcurrencyStrategy(cacheConcurrentStrategy);
            rootClass.setCacheRegionName(cacheRegion);
            rootClass.setLazyPropertiesCacheable(cacheLazyProperty);
        }
        rootClass.setNaturalIdCacheRegionName(naturalIdCacheRegion);
        boolean forceDiscriminatorInSelects = forceDiscriminator == null ? context.getBuildingOptions().shouldImplicitlyForceDiscriminatorInSelect() : forceDiscriminator;
        rootClass.setForceDiscriminator(forceDiscriminatorInSelects);
        if (insertableDiscriminator != null) {
            rootClass.setDiscriminatorInsertable(insertableDiscriminator);
        }
    } else {
        if (explicitHibernateEntityAnnotation) {
            LOG.entityAnnotationOnNonRoot(annotatedClass.getName());
        }
        if (annotatedClass.isAnnotationPresent(Immutable.class)) {
            LOG.immutableAnnotationOnNonRoot(annotatedClass.getName());
        }
    }
    persistentClass.setCached(isCached);
    persistentClass.setOptimisticLockStyle(getVersioning(optimisticLockType));
    persistentClass.setSelectBeforeUpdate(selectBeforeUpdate);
    // set persister if needed
    Persister persisterAnn = annotatedClass.getAnnotation(Persister.class);
    Class persister = null;
    if (persisterAnn != null) {
        persister = persisterAnn.impl();
    } else {
        org.hibernate.annotations.Entity entityAnn = annotatedClass.getAnnotation(org.hibernate.annotations.Entity.class);
        if (entityAnn != null && !BinderHelper.isEmptyAnnotationValue(entityAnn.persister())) {
            try {
                persister = context.getBootstrapContext().getClassLoaderAccess().classForName(entityAnn.persister());
            } catch (ClassLoadingException e) {
                throw new AnnotationException("Could not find persister class: " + entityAnn.persister(), e);
            }
        }
    }
    if (persister != null) {
        persistentClass.setEntityPersisterClass(persister);
    }
    persistentClass.setBatchSize(batchSize);
    // SQL overriding
    SQLInsert sqlInsert = annotatedClass.getAnnotation(SQLInsert.class);
    SQLUpdate sqlUpdate = annotatedClass.getAnnotation(SQLUpdate.class);
    SQLDelete sqlDelete = annotatedClass.getAnnotation(SQLDelete.class);
    SQLDeleteAll sqlDeleteAll = annotatedClass.getAnnotation(SQLDeleteAll.class);
    Loader loader = annotatedClass.getAnnotation(Loader.class);
    if (sqlInsert != null) {
        persistentClass.setCustomSQLInsert(sqlInsert.sql().trim(), sqlInsert.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlInsert.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (sqlUpdate != null) {
        persistentClass.setCustomSQLUpdate(sqlUpdate.sql(), sqlUpdate.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlUpdate.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (sqlDelete != null) {
        persistentClass.setCustomSQLDelete(sqlDelete.sql(), sqlDelete.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlDelete.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (sqlDeleteAll != null) {
        persistentClass.setCustomSQLDelete(sqlDeleteAll.sql(), sqlDeleteAll.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlDeleteAll.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (loader != null) {
        persistentClass.setLoaderName(loader.namedQuery());
    }
    final JdbcEnvironment jdbcEnvironment = context.getMetadataCollector().getDatabase().getJdbcEnvironment();
    if (annotatedClass.isAnnotationPresent(Synchronize.class)) {
        Synchronize synchronizedWith = annotatedClass.getAnnotation(Synchronize.class);
        String[] tables = synchronizedWith.value();
        for (String table : tables) {
            persistentClass.addSynchronizedTable(context.getBuildingOptions().getPhysicalNamingStrategy().toPhysicalTableName(jdbcEnvironment.getIdentifierHelper().toIdentifier(table), jdbcEnvironment).render(jdbcEnvironment.getDialect()));
        }
    }
    if (annotatedClass.isAnnotationPresent(Subselect.class)) {
        Subselect subselect = annotatedClass.getAnnotation(Subselect.class);
        this.subselect = subselect.value();
    }
    // tuplizers
    if (annotatedClass.isAnnotationPresent(Tuplizers.class)) {
        for (Tuplizer tuplizer : annotatedClass.getAnnotation(Tuplizers.class).value()) {
            EntityMode mode = EntityMode.parse(tuplizer.entityMode());
            // todo tuplizer.entityModeType
            persistentClass.addTuplizer(mode, tuplizer.impl().getName());
        }
    }
    if (annotatedClass.isAnnotationPresent(Tuplizer.class)) {
        Tuplizer tuplizer = annotatedClass.getAnnotation(Tuplizer.class);
        EntityMode mode = EntityMode.parse(tuplizer.entityMode());
        // todo tuplizer.entityModeType
        persistentClass.addTuplizer(mode, tuplizer.impl().getName());
    }
    for (Filter filter : filters) {
        String filterName = filter.name();
        String cond = filter.condition();
        if (BinderHelper.isEmptyAnnotationValue(cond)) {
            FilterDefinition definition = context.getMetadataCollector().getFilterDefinition(filterName);
            cond = definition == null ? null : definition.getDefaultFilterCondition();
            if (StringHelper.isEmpty(cond)) {
                throw new AnnotationException("no filter condition found for filter " + filterName + " in " + this.name);
            }
        }
        persistentClass.addFilter(filterName, cond, filter.deduceAliasInjectionPoints(), toAliasTableMap(filter.aliases()), toAliasEntityMap(filter.aliases()));
    }
    LOG.debugf("Import with entity name %s", name);
    try {
        context.getMetadataCollector().addImport(name, persistentClass.getEntityName());
        String entityName = persistentClass.getEntityName();
        if (!entityName.equals(name)) {
            context.getMetadataCollector().addImport(entityName, entityName);
        }
    } catch (MappingException me) {
        throw new AnnotationException("Use of the same entity name twice: " + name, me);
    }
    processNamedEntityGraphs();
}
Also used : Synchronize(org.hibernate.annotations.Synchronize) Loader(org.hibernate.annotations.Loader) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) MappingException(org.hibernate.MappingException) FilterDefinition(org.hibernate.engine.spi.FilterDefinition) AnnotationException(org.hibernate.AnnotationException) SQLInsert(org.hibernate.annotations.SQLInsert) Persister(org.hibernate.annotations.Persister) RootClass(org.hibernate.mapping.RootClass) Tuplizer(org.hibernate.annotations.Tuplizer) ClassLoadingException(org.hibernate.boot.registry.classloading.spi.ClassLoadingException) Subselect(org.hibernate.annotations.Subselect) SQLDelete(org.hibernate.annotations.SQLDelete) EntityMode(org.hibernate.EntityMode) Filter(org.hibernate.annotations.Filter) PersistentClass(org.hibernate.mapping.PersistentClass) RootClass(org.hibernate.mapping.RootClass) XClass(org.hibernate.annotations.common.reflection.XClass) SQLUpdate(org.hibernate.annotations.SQLUpdate) SQLDeleteAll(org.hibernate.annotations.SQLDeleteAll) Tuplizers(org.hibernate.annotations.Tuplizers)

Aggregations

EntityMode (org.hibernate.EntityMode)12 RootClass (org.hibernate.mapping.RootClass)4 ArrayList (java.util.ArrayList)3 PersistentCollection (org.hibernate.collection.spi.PersistentCollection)3 CollectionKey (org.hibernate.engine.spi.CollectionKey)3 Column (org.hibernate.mapping.Column)3 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Tuplizer (org.hibernate.annotations.Tuplizer)2 Tuplizers (org.hibernate.annotations.Tuplizers)2 ClassLoadingException (org.hibernate.boot.registry.classloading.spi.ClassLoadingException)2 Configuration (org.hibernate.cfg.Configuration)2 AbstractPersistentCollection (org.hibernate.collection.internal.AbstractPersistentCollection)2 SessionFactoryImplementor (org.hibernate.engine.SessionFactoryImplementor)2 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)2 FilterDefinition (org.hibernate.engine.spi.FilterDefinition)2 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)2 SessionFactoryImpl (org.hibernate.impl.SessionFactoryImpl)2 PersistentClass (org.hibernate.mapping.PersistentClass)2 SimpleValue (org.hibernate.mapping.SimpleValue)2