Search in sources :

Example 51 with CollectionPersister

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

the class StatefulPersistenceContext method getOwnerId.

@Override
public Serializable getOwnerId(String entityName, String propertyName, Object childEntity, Map mergeMap) {
    final String collectionRole = entityName + '.' + propertyName;
    final EntityPersister persister = session.getFactory().getMetamodel().entityPersister(entityName);
    final CollectionPersister collectionPersister = session.getFactory().getMetamodel().collectionPersister(collectionRole);
    // try cache lookup first
    final Object parent = parentsByChild.get(childEntity);
    if (parent != null) {
        final EntityEntry entityEntry = entityEntryContext.getEntityEntry(parent);
        // there maybe more than one parent, filter by type
        if (persister.isSubclassEntityName(entityEntry.getEntityName()) && isFoundInParent(propertyName, childEntity, persister, collectionPersister, parent)) {
            return getEntry(parent).getId();
        } else {
            // remove wrong entry
            parentsByChild.remove(childEntity);
        }
    }
    // iterate all the entities currently associated with the persistence context.
    for (Entry<Object, EntityEntry> me : reentrantSafeEntityEntries()) {
        final EntityEntry entityEntry = me.getValue();
        // does this entity entry pertain to the entity persister in which we are interested (owner)?
        if (persister.isSubclassEntityName(entityEntry.getEntityName())) {
            final Object entityEntryInstance = me.getKey();
            // check if the managed object is the parent
            boolean found = isFoundInParent(propertyName, childEntity, persister, collectionPersister, entityEntryInstance);
            if (!found && mergeMap != null) {
                // check if the detached object being merged is the parent
                final Object unmergedInstance = mergeMap.get(entityEntryInstance);
                final Object unmergedChild = mergeMap.get(childEntity);
                if (unmergedInstance != null && unmergedChild != null) {
                    found = isFoundInParent(propertyName, unmergedChild, persister, collectionPersister, unmergedInstance);
                    LOG.debugf("Detached object being merged (corresponding with a managed entity) has a collection that [%s] the detached child.", (found ? "contains" : "does not contain"));
                }
            }
            if (found) {
                return entityEntry.getId();
            }
        }
    }
    // of the loop-in-loop especially considering this is far more likely the 'edge case'
    if (mergeMap != null) {
        for (Object o : mergeMap.entrySet()) {
            final Entry mergeMapEntry = (Entry) o;
            if (mergeMapEntry.getKey() instanceof HibernateProxy) {
                final HibernateProxy proxy = (HibernateProxy) mergeMapEntry.getKey();
                if (persister.isSubclassEntityName(proxy.getHibernateLazyInitializer().getEntityName())) {
                    boolean found = isFoundInParent(propertyName, childEntity, persister, collectionPersister, mergeMap.get(proxy));
                    LOG.debugf("Detached proxy being merged has a collection that [%s] the managed child.", (found ? "contains" : "does not contain"));
                    if (!found) {
                        found = isFoundInParent(propertyName, mergeMap.get(childEntity), persister, collectionPersister, mergeMap.get(proxy));
                        LOG.debugf("Detached proxy being merged has a collection that [%s] the detached child being merged..", (found ? "contains" : "does not contain"));
                    }
                    if (found) {
                        return proxy.getHibernateLazyInitializer().getIdentifier();
                    }
                }
            }
        }
    }
    return null;
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityEntry(org.hibernate.engine.spi.EntityEntry) CollectionEntry(org.hibernate.engine.spi.CollectionEntry) Entry(java.util.Map.Entry) EntityEntry(org.hibernate.engine.spi.EntityEntry) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) HibernateProxy(org.hibernate.proxy.HibernateProxy)

Example 52 with CollectionPersister

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

the class MetamodelImpl method initialize.

/**
 * Prepare the metamodel using the information from the collection of Hibernate
 * {@link PersistentClass} models
 *
 * @param mappingMetadata The mapping information
 * @param jpaMetaModelPopulationSetting Should the JPA Metamodel be built as well?
 */
public void initialize(MetadataImplementor mappingMetadata, JpaMetaModelPopulationSetting jpaMetaModelPopulationSetting) {
    this.imports.putAll(mappingMetadata.getImports());
    primeSecondLevelCacheRegions(mappingMetadata);
    final PersisterCreationContext persisterCreationContext = new PersisterCreationContext() {

        @Override
        public SessionFactoryImplementor getSessionFactory() {
            return sessionFactory;
        }

        @Override
        public MetadataImplementor getMetadata() {
            return mappingMetadata;
        }
    };
    final PersisterFactory persisterFactory = sessionFactory.getServiceRegistry().getService(PersisterFactory.class);
    for (final PersistentClass model : mappingMetadata.getEntityBindings()) {
        final NavigableRole rootEntityRole = new NavigableRole(model.getRootClass().getEntityName());
        final EntityDataAccess accessStrategy = sessionFactory.getCache().getEntityRegionAccess(rootEntityRole);
        final NaturalIdDataAccess naturalIdAccessStrategy = sessionFactory.getCache().getNaturalIdCacheRegionAccessStrategy(rootEntityRole);
        final EntityPersister cp = persisterFactory.createEntityPersister(model, accessStrategy, naturalIdAccessStrategy, persisterCreationContext);
        entityPersisterMap.put(model.getEntityName(), cp);
        if (cp.getConcreteProxyClass() != null && cp.getConcreteProxyClass().isInterface() && !Map.class.isAssignableFrom(cp.getConcreteProxyClass()) && cp.getMappedClass() != cp.getConcreteProxyClass()) {
            if (cp.getMappedClass().equals(cp.getConcreteProxyClass())) {
                // this part handles an odd case in the Hibernate test suite where we map an interface
                // as the class and the proxy.  I cannot think of a real life use case for that
                // specific test, but..
                log.debugf("Entity [%s] mapped same interface [%s] as class and proxy", cp.getEntityName(), cp.getMappedClass());
            } else {
                final String old = entityProxyInterfaceMap.put(cp.getConcreteProxyClass(), cp.getEntityName());
                if (old != null) {
                    throw new HibernateException(String.format(Locale.ENGLISH, "Multiple entities [%s, %s] named the same interface [%s] as their proxy which is not supported", old, cp.getEntityName(), cp.getConcreteProxyClass().getName()));
                }
            }
        }
    }
    for (final Collection model : mappingMetadata.getCollectionBindings()) {
        final NavigableRole navigableRole = new NavigableRole(model.getRole());
        final CollectionDataAccess accessStrategy = sessionFactory.getCache().getCollectionRegionAccess(navigableRole);
        final CollectionPersister persister = persisterFactory.createCollectionPersister(model, accessStrategy, persisterCreationContext);
        collectionPersisterMap.put(model.getRole(), persister);
        Type indexType = persister.getIndexType();
        if (indexType != null && indexType.isAssociationType() && !indexType.isAnyType()) {
            String entityName = ((AssociationType) indexType).getAssociatedEntityName(sessionFactory);
            Set<String> roles = collectionRolesByEntityParticipant.get(entityName);
            if (roles == null) {
                roles = new HashSet<>();
                collectionRolesByEntityParticipant.put(entityName, roles);
            }
            roles.add(persister.getRole());
        }
        Type elementType = persister.getElementType();
        if (elementType.isAssociationType() && !elementType.isAnyType()) {
            String entityName = ((AssociationType) elementType).getAssociatedEntityName(sessionFactory);
            Set<String> roles = collectionRolesByEntityParticipant.get(entityName);
            if (roles == null) {
                roles = new HashSet<>();
                collectionRolesByEntityParticipant.put(entityName, roles);
            }
            roles.add(persister.getRole());
        }
    }
    // after *all* persisters and named queries are registered
    entityPersisterMap.values().forEach(EntityPersister::generateEntityDefinition);
    for (EntityPersister persister : entityPersisterMap.values()) {
        persister.postInstantiate();
        registerEntityNameResolvers(persister, entityNameResolvers);
    }
    collectionPersisterMap.values().forEach(CollectionPersister::postInstantiate);
    if (jpaMetaModelPopulationSetting != JpaMetaModelPopulationSetting.DISABLED) {
        MetadataContext context = new MetadataContext(sessionFactory, mappingMetadata.getMappedSuperclassMappingsCopy(), jpaMetaModelPopulationSetting);
        for (PersistentClass entityBinding : mappingMetadata.getEntityBindings()) {
            locateOrBuildEntityType(entityBinding, context);
        }
        handleUnusedMappedSuperclasses(context);
        context.wrapUp();
        this.jpaEntityTypeMap.putAll(context.getEntityTypeMap());
        this.jpaEmbeddableTypeMap.putAll(context.getEmbeddableTypeMap());
        this.jpaMappedSuperclassTypeMap.putAll(context.getMappedSuperclassTypeMap());
        this.jpaEntityTypesByEntityName.putAll(context.getEntityTypesByEntityName());
        applyNamedEntityGraphs(mappingMetadata.getNamedEntityGraphs().values());
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) HibernateException(org.hibernate.HibernateException) PersisterFactory(org.hibernate.persister.spi.PersisterFactory) NaturalIdDataAccess(org.hibernate.cache.spi.access.NaturalIdDataAccess) CollectionDataAccess(org.hibernate.cache.spi.access.CollectionDataAccess) PersisterCreationContext(org.hibernate.persister.spi.PersisterCreationContext) AccessType(org.hibernate.cache.spi.access.AccessType) ManagedType(javax.persistence.metamodel.ManagedType) MappedSuperclassType(javax.persistence.metamodel.MappedSuperclassType) EntityType(javax.persistence.metamodel.EntityType) AssociationType(org.hibernate.type.AssociationType) EmbeddableType(javax.persistence.metamodel.EmbeddableType) Type(org.hibernate.type.Type) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) AssociationType(org.hibernate.type.AssociationType) NavigableRole(org.hibernate.metamodel.model.domain.NavigableRole) Collection(org.hibernate.mapping.Collection) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) PersistentClass(org.hibernate.mapping.PersistentClass) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess)

Example 53 with CollectionPersister

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

the class CacheLazyLoadNoTransTest method isCached.

private boolean isCached(Serializable id, Class<?> entityClass, String attr) {
    Session session = openSession();
    CollectionPersister persister = sessionFactory().getCollectionPersister(entityClass.getName() + "." + attr);
    CollectionDataAccess cache = persister.getCacheAccessStrategy();
    Object key = cache.generateCacheKey(id, persister, sessionFactory(), session.getTenantIdentifier());
    Object cachedValue = cache.get(((SessionImplementor) session), key);
    session.close();
    return cachedValue != null;
}
Also used : CollectionPersister(org.hibernate.persister.collection.CollectionPersister) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) CollectionDataAccess(org.hibernate.cache.spi.access.CollectionDataAccess) Session(org.hibernate.Session)

Example 54 with CollectionPersister

use of org.hibernate.persister.collection.CollectionPersister in project jbpm by kiegroup.

the class DistincVsJoinPerformanceTest method copyCollectionPersisterKeys.

private void copyCollectionPersisterKeys(Attribute embeddedAttr, PluralAttribute listAttr, EntityManager em) {
    String[] keys = createOriginalAndExpectedKeys(embeddedAttr, listAttr);
    try {
        SessionImpl session = (SessionImpl) em.getDelegate();
        SessionFactoryImplementor sessionFactory = session.getSessionFactory();
        CollectionPersister persister = sessionFactory.getCollectionPersister(keys[0]);
        sessionFactory.getCollectionPersisters().put(keys[1], persister);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : CollectionPersister(org.hibernate.persister.collection.CollectionPersister) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SessionImpl(org.hibernate.internal.SessionImpl)

Example 55 with CollectionPersister

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

the class HibernatePropertyIntrospector method initCollectionProperty.

private void initCollectionProperty(MetamodelImplementor metamodelImplementor, Property property, CollectionType type) {
    CollectionPersister persister = metamodelImplementor.collectionPersister(type.getRole());
    property.setOwner(!persister.isInverse());
    property.setManyToMany(persister.isManyToMany());
    property.setOneToMany(persister.isOneToMany());
    property.setMin(0d);
    property.setMax(Double.MAX_VALUE);
    if (property.isOwner()) {
        property.setOwningRole(type.getRole());
        property.setInverseRole(roleToRole.get(type.getRole()));
    } else {
        property.setOwningRole(roleToRole.get(type.getRole()));
        property.setInverseRole(type.getRole());
    }
}
Also used : CollectionPersister(org.hibernate.persister.collection.CollectionPersister)

Aggregations

CollectionPersister (org.hibernate.persister.collection.CollectionPersister)55 HibernateException (org.hibernate.HibernateException)11 Type (org.hibernate.type.Type)10 PersistentCollection (org.hibernate.collection.spi.PersistentCollection)9 CollectionType (org.hibernate.type.CollectionType)9 Serializable (java.io.Serializable)8 HashMap (java.util.HashMap)8 Map (java.util.Map)8 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)8 EntityPersister (org.hibernate.persister.entity.EntityPersister)7 Session (org.hibernate.Session)6 CollectionDataAccess (org.hibernate.cache.spi.access.CollectionDataAccess)6 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)6 Test (org.junit.Test)6 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 ArrayList (java.util.ArrayList)4