Search in sources :

Example 6 with EntityPersister

use of org.hibernate.persister.entity.EntityPersister in project hibernate-orm by hibernate.

the class StructuredCacheEntry method destructure.

@Override
@SuppressWarnings("unchecked")
public Object destructure(Object structured, SessionFactoryImplementor factory) {
    final Map map = (Map) structured;
    final String subclass = (String) map.get(SUBCLASS_KEY);
    final Object version = map.get(VERSION_KEY);
    final EntityPersister subclassPersister = factory.getEntityPersister(subclass);
    final String[] names = subclassPersister.getPropertyNames();
    final Serializable[] state = new Serializable[names.length];
    for (int i = 0; i < names.length; i++) {
        state[i] = (Serializable) map.get(names[i]);
    }
    return new StandardCacheEntryImpl(state, TypeHelper.toLoggableString(state, subclassPersister.getPropertyTypes(), factory), subclass, version);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) Map(java.util.Map) HashMap(java.util.HashMap)

Example 7 with EntityPersister

use of org.hibernate.persister.entity.EntityPersister in project hibernate-orm by hibernate.

the class Example method getTypedValues.

@Override
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) {
    final EntityPersister meta = criteriaQuery.getFactory().getEntityPersister(criteriaQuery.getEntityName(criteria));
    final String[] propertyNames = meta.getPropertyNames();
    final Type[] propertyTypes = meta.getPropertyTypes();
    final Object[] values = meta.getPropertyValues(exampleEntity);
    final List<TypedValue> list = new ArrayList<TypedValue>();
    for (int i = 0; i < propertyNames.length; i++) {
        final Object value = values[i];
        final Type type = propertyTypes[i];
        final String name = propertyNames[i];
        final boolean isVersionProperty = i == meta.getVersionProperty();
        if (!isVersionProperty && isPropertyIncluded(value, name, type)) {
            if (propertyTypes[i].isComponentType()) {
                addComponentTypedValues(name, value, (CompositeType) type, list, criteria, criteriaQuery);
            } else {
                addPropertyTypedValue(value, type, list);
            }
        }
    }
    return list.toArray(new TypedValue[list.size()]);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) CompositeType(org.hibernate.type.CompositeType) Type(org.hibernate.type.Type) ArrayList(java.util.ArrayList) TypedValue(org.hibernate.engine.spi.TypedValue)

Example 8 with EntityPersister

use of org.hibernate.persister.entity.EntityPersister in project hibernate-orm by hibernate.

the class Example method toSqlString.

@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) {
    final StringBuilder buf = new StringBuilder().append('(');
    final EntityPersister meta = criteriaQuery.getFactory().getEntityPersister(criteriaQuery.getEntityName(criteria));
    final String[] propertyNames = meta.getPropertyNames();
    final Type[] propertyTypes = meta.getPropertyTypes();
    final Object[] propertyValues = meta.getPropertyValues(exampleEntity);
    for (int i = 0; i < propertyNames.length; i++) {
        final Object propertyValue = propertyValues[i];
        final String propertyName = propertyNames[i];
        final boolean isVersionProperty = i == meta.getVersionProperty();
        if (!isVersionProperty && isPropertyIncluded(propertyValue, propertyName, propertyTypes[i])) {
            if (propertyTypes[i].isComponentType()) {
                appendComponentCondition(propertyName, propertyValue, (CompositeType) propertyTypes[i], criteria, criteriaQuery, buf);
            } else {
                appendPropertyCondition(propertyName, propertyValue, criteria, criteriaQuery, buf);
            }
        }
    }
    if (buf.length() == 1) {
        buf.append("1=1");
    }
    return buf.append(')').toString();
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) CompositeType(org.hibernate.type.CompositeType) Type(org.hibernate.type.Type)

Example 9 with EntityPersister

use of org.hibernate.persister.entity.EntityPersister in project hibernate-orm by hibernate.

the class TwoPhaseLoad method doInitializeEntity.

private static void doInitializeEntity(final Object entity, final EntityEntry entityEntry, final boolean readOnly, final SharedSessionContractImplementor session, final PreLoadEvent preLoadEvent) throws HibernateException {
    final PersistenceContext persistenceContext = session.getPersistenceContext();
    final EntityPersister persister = entityEntry.getPersister();
    final Serializable id = entityEntry.getId();
    final Object[] hydratedState = entityEntry.getLoadedState();
    final boolean debugEnabled = LOG.isDebugEnabled();
    if (debugEnabled) {
        LOG.debugf("Resolving associations for %s", MessageHelper.infoString(persister, id, session.getFactory()));
    }
    final Type[] types = persister.getPropertyTypes();
    for (int i = 0; i < hydratedState.length; i++) {
        final Object value = hydratedState[i];
        if (value == LazyPropertyInitializer.UNFETCHED_PROPERTY) {
            // No resolution is necessary, unless the lazy property is a collection.
            if (types[i].isCollectionType()) {
                // IMPLEMENTATION NOTE: this is a lazy collection property on a bytecode-enhanced entity.
                // HHH-10989: We need to resolve the collection so that a CollectionReference is added to StatefulPersistentContext.
                // As mentioned above, hydratedState[i] needs to remain LazyPropertyInitializer.UNFETCHED_PROPERTY
                // so do not assign the resolved, unitialized PersistentCollection back to hydratedState[i].
                types[i].resolve(value, session, entity);
            }
        } else if (value != PropertyAccessStrategyBackRefImpl.UNKNOWN) {
            // we know value != LazyPropertyInitializer.UNFETCHED_PROPERTY
            hydratedState[i] = types[i].resolve(value, session, entity);
        }
    }
    //Must occur afterQuery resolving identifiers!
    if (session.isEventSource()) {
        preLoadEvent.setEntity(entity).setState(hydratedState).setId(id).setPersister(persister);
        final EventListenerGroup<PreLoadEventListener> listenerGroup = session.getFactory().getServiceRegistry().getService(EventListenerRegistry.class).getEventListenerGroup(EventType.PRE_LOAD);
        for (PreLoadEventListener listener : listenerGroup.listeners()) {
            listener.onPreLoad(preLoadEvent);
        }
    }
    persister.setPropertyValues(entity, hydratedState);
    final SessionFactoryImplementor factory = session.getFactory();
    if (persister.hasCache() && session.getCacheMode().isPutEnabled()) {
        if (debugEnabled) {
            LOG.debugf("Adding entity to second-level cache: %s", MessageHelper.infoString(persister, id, session.getFactory()));
        }
        final Object version = Versioning.getVersion(hydratedState, persister);
        final CacheEntry entry = persister.buildCacheEntry(entity, hydratedState, version, session);
        final EntityRegionAccessStrategy cache = persister.getCacheAccessStrategy();
        final Object cacheKey = cache.generateCacheKey(id, persister, factory, session.getTenantIdentifier());
        // we need to be careful not to clobber the lock here in the cache so that it can be rolled back if need be
        if (session.getPersistenceContext().wasInsertedDuringTransaction(persister, id)) {
            cache.update(session, cacheKey, persister.getCacheEntryStructure().structure(entry), version, version);
        } else {
            final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
            try {
                eventListenerManager.cachePutStart();
                final boolean put = cache.putFromLoad(session, cacheKey, persister.getCacheEntryStructure().structure(entry), session.getTimestamp(), version, useMinimalPuts(session, entityEntry));
                if (put && factory.getStatistics().isStatisticsEnabled()) {
                    factory.getStatistics().secondLevelCachePut(cache.getRegion().getName());
                }
            } finally {
                eventListenerManager.cachePutEnd();
            }
        }
    }
    if (persister.hasNaturalIdentifier()) {
        persistenceContext.getNaturalIdHelper().cacheNaturalIdCrossReferenceFromLoad(persister, id, persistenceContext.getNaturalIdHelper().extractNaturalIdValues(hydratedState, persister));
    }
    boolean isReallyReadOnly = readOnly;
    if (!persister.isMutable()) {
        isReallyReadOnly = true;
    } else {
        final Object proxy = persistenceContext.getProxy(entityEntry.getEntityKey());
        if (proxy != null) {
            // there is already a proxy for this impl
            // only set the status to read-only if the proxy is read-only
            isReallyReadOnly = ((HibernateProxy) proxy).getHibernateLazyInitializer().isReadOnly();
        }
    }
    if (isReallyReadOnly) {
        //no need to take a snapshot - this is a
        //performance optimization, but not really
        //important, except for entities with huge
        //mutable property values
        persistenceContext.setEntryStatus(entityEntry, Status.READ_ONLY);
    } else {
        //take a snapshot
        TypeHelper.deepCopy(hydratedState, persister.getPropertyTypes(), persister.getPropertyUpdateability(), //afterQuery setting values to object
        hydratedState, session);
        persistenceContext.setEntryStatus(entityEntry, Status.MANAGED);
    }
    persister.afterInitialize(entity, session);
    if (debugEnabled) {
        LOG.debugf("Done materializing entity %s", MessageHelper.infoString(persister, id, session.getFactory()));
    }
    if (factory.getStatistics().isStatisticsEnabled()) {
        factory.getStatistics().loadEntity(persister.getEntityName());
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EntityRegionAccessStrategy(org.hibernate.cache.spi.access.EntityRegionAccessStrategy) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) PreLoadEventListener(org.hibernate.event.spi.PreLoadEventListener) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry) HibernateProxy(org.hibernate.proxy.HibernateProxy) EventListenerRegistry(org.hibernate.event.service.spi.EventListenerRegistry) EventType(org.hibernate.event.spi.EventType) Type(org.hibernate.type.Type) SessionEventListenerManager(org.hibernate.engine.spi.SessionEventListenerManager)

Example 10 with EntityPersister

use of org.hibernate.persister.entity.EntityPersister in project hibernate-orm by hibernate.

the class PessimisticForceIncrementLockingStrategy method lock.

@Override
public void lock(Serializable id, Object version, Object object, int timeout, SharedSessionContractImplementor session) {
    if (!lockable.isVersioned()) {
        throw new HibernateException("[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]");
    }
    final EntityEntry entry = session.getPersistenceContext().getEntry(object);
    final EntityPersister persister = entry.getPersister();
    final Object nextVersion = persister.forceVersionIncrement(entry.getId(), entry.getVersion(), session);
    entry.forceLocked(object, nextVersion);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityEntry(org.hibernate.engine.spi.EntityEntry) HibernateException(org.hibernate.HibernateException)

Aggregations

EntityPersister (org.hibernate.persister.entity.EntityPersister)166 Test (org.junit.Test)59 Serializable (java.io.Serializable)34 Session (org.hibernate.Session)31 Type (org.hibernate.type.Type)29 EntityEntry (org.hibernate.engine.spi.EntityEntry)21 EventSource (org.hibernate.event.spi.EventSource)15 EntityRegionAccessStrategy (org.hibernate.cache.spi.access.EntityRegionAccessStrategy)13 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)13 TestForIssue (org.hibernate.testing.TestForIssue)13 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)12 SequenceStyleGenerator (org.hibernate.id.enhanced.SequenceStyleGenerator)12 EntityType (org.hibernate.type.EntityType)12 ArrayList (java.util.ArrayList)11 CompositeType (org.hibernate.type.CompositeType)11 HibernateProxy (org.hibernate.proxy.HibernateProxy)10 PreparedStatement (java.sql.PreparedStatement)8 List (java.util.List)8 EntityKey (org.hibernate.engine.spi.EntityKey)8 QueryParameters (org.hibernate.engine.spi.QueryParameters)8