Java Examples for org.hibernate.engine.spi.EntityEntry

The following java examples will help you to understand the usage of org.hibernate.engine.spi.EntityEntry. These source code samples are taken from different open source projects.

Example 1
Project: hibernate-orm-master  File: Loader.java View source code
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 before 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 after 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 after two-phase load");
                    }
                    afterLoadAction.afterLoad(session, hydratedObject, (Loadable) entityEntry.getPersister());
                }
            }
        }
    }
}
Example 2
Project: webofneeds-master  File: ParentAwareFlushEventListener.java View source code
@Override
public void onFlushEntity(final FlushEntityEvent event) throws HibernateException {
    final EntityEntry entry = event.getEntityEntry();
    final Object entity = event.getEntity();
    final boolean mightBeDirty = entry.requiresDirtyCheck(entity);
    if (mightBeDirty && entity instanceof ParentAware) {
        ParentAware parentAware = (ParentAware) entity;
        if (updated(event)) {
            VersionedEntity parent = parentAware.getParent();
            if (parent == null)
                return;
            if (logger.isDebugEnabled()) {
                logger.debug("Incrementing {} entity version because a {} child entity has been updated", parent, entity);
            }
            if (!(parent instanceof HibernateProxy)) {
                //we have to do the increment manually
                parent.incrementVersion();
            }
            Hibernate.initialize(parent);
            event.getSession().save(parent);
        } else if (deleted(event)) {
            VersionedEntity parent = parentAware.getParent();
            if (parent == null)
                return;
            if (logger.isDebugEnabled()) {
                logger.debug("Incrementing {} entity version because a {} child entity has been deleted", root, entity);
            }
            if (!(parent instanceof HibernateProxy)) {
                //we have to do the increment manually
                parent.incrementVersion();
            }
            Hibernate.initialize(parent);
            event.getSession().save(parent);
        }
    }
}
Example 3
Project: hibernate-ogm-master  File: OgmEntityEntryState.java View source code
public static OgmEntityEntryState getStateFor(SessionImplementor session, Object object) {
    EntityEntry entityEntry = session.getPersistenceContext().getEntry(object);
    if (entityEntry == null) {
        throw log.cannotFindEntityEntryForEntity(object);
    }
    OgmEntityEntryState ogmEntityState = entityEntry.getExtraState(OgmEntityEntryState.class);
    if (ogmEntityState == null) {
        ogmEntityState = new OgmEntityEntryState();
        entityEntry.addExtraState(ogmEntityState);
    }
    return ogmEntityState;
}
Example 4
Project: clinic-softacad-master  File: CollectionType.java View source code
/**
	 * Get the key value from the owning entity instance, usually the identifier, but might be some
	 * other unique key, in the case of property-ref
	 *
	 * @param owner The collection owner
	 * @param session The session from which the request is originating.
	 * @return The collection owner's key
	 */
public Serializable getKeyOfOwner(Object owner, SessionImplementor session) {
    EntityEntry entityEntry = session.getPersistenceContext().getEntry(owner);
    // This just handles a particular case of component
    if (entityEntry == null)
        return null;
    if (foreignKeyPropertyName == null) {
        return entityEntry.getId();
    } else {
        // TODO: at the point where we are resolving collection references, we don't
        // know if the uk value has been resolved (depends if it was earlier or
        // later in the mapping document) - now, we could try and use e.getStatus()
        // to decide to semiResolve(), trouble is that initializeEntity() reuses
        // the same array for resolved and hydrated values
        Object id;
        if (entityEntry.getLoadedState() != null) {
            id = entityEntry.getLoadedValue(foreignKeyPropertyName);
        } else {
            id = entityEntry.getPersister().getPropertyValue(owner, foreignKeyPropertyName);
        }
        // NOTE VERY HACKISH WORKAROUND!!
        // TODO: Fix this so it will work for non-POJO entity mode
        Type keyType = getPersister(session).getKeyType();
        if (!keyType.getReturnedClass().isInstance(id)) {
            id = (Serializable) keyType.semiResolve(entityEntry.getLoadedValue(foreignKeyPropertyName), session, owner);
        }
        return (Serializable) id;
    }
}
Example 5
Project: hibernate-core-ogm-master  File: SessionImpl.java View source code
public LockMode getCurrentLockMode(Object object) throws HibernateException {
    errorIfClosed();
    checkTransactionSynchStatus();
    if (object == null) {
        throw new NullPointerException("null object passed to getCurrentLockMode()");
    }
    if (object instanceof HibernateProxy) {
        object = ((HibernateProxy) object).getHibernateLazyInitializer().getImplementation(this);
        if (object == null) {
            return LockMode.NONE;
        }
    }
    EntityEntry e = persistenceContext.getEntry(object);
    if (e == null) {
        throw new TransientObjectException("Given object not associated with the session");
    }
    if (e.getStatus() != Status.MANAGED) {
        throw new ObjectDeletedException("The given object was deleted", e.getId(), e.getPersister().getEntityName());
    }
    return e.getLockMode();
}
Example 6
Project: jvm-tools-master  File: JBossServerDumpExample.java View source code
/**
     * This example finds and reports Hibernate entities in dump.
     */
@Test
public void printEnties() throws IOException {
    Map<String, Integer> histo = new TreeMap<String, Integer>();
    JavaClass jc = heap.getJavaClassByName("org.hibernate.engine.spi.EntityEntry");
    for (Instance i : jc.getInstances()) {
        try {
            String name = "" + valueOf(i, "entityName");
            //                String rowId = "" + valueOf(i, "rowId");
            System.out.println(i.getInstanceId() + "\t" + name);
            int n = histo.containsKey(name) ? histo.get(name) : 0;
            histo.put(name, n + 1);
        } catch (IllegalArgumentException e) {
            System.err.println(e);
        }
    }
    System.out.println();
    for (String type : histo.keySet()) {
        System.out.println(type + "\t" + histo.get(type));
    }
}
Example 7
Project: hibernate-search-master  File: FullTextIndexEventListener.java View source code
private Serializable getId(Object entity, AbstractCollectionEvent event) {
    Serializable id = event.getAffectedOwnerIdOrNull();
    if (id == null) {
        // most likely this recovery is unnecessary since Hibernate Core probably try that
        EntityEntry entityEntry = event.getSession().getPersistenceContext().getEntry(entity);
        id = entityEntry == null ? null : entityEntry.getId();
    }
    return id;
}
Example 8
Project: Hibernate-Search-GenericJPA-master  File: HibernateUpdateSource.java View source code
private Serializable getId(Object entity, AbstractCollectionEvent event) {
    Serializable id = event.getAffectedOwnerIdOrNull();
    if (id == null) {
        // most likely this recovery is unnecessary since Hibernate Core probably try that
        EntityEntry entityEntry = event.getSession().getPersistenceContext().getEntry(entity);
        id = entityEntry == null ? null : entityEntry.getId();
    }
    return id;
}
Example 9
Project: Gorm-master  File: GrailsHibernateUtil.java View source code
/**
     * Sets the target object to read-write, allowing Hibernate to dirty check it and auto-flush changes.
     *
     * @see #setObjectToReadyOnly(Object, org.hibernate.SessionFactory)
     *
     * @param target The target object
     * @param sessionFactory The SessionFactory instance
     */
public static void setObjectToReadWrite(final Object target, SessionFactory sessionFactory) {
    Session session = sessionFactory.getCurrentSession();
    if (!canModifyReadWriteState(session, target)) {
        return;
    }
    SessionImplementor sessionImpl = (SessionImplementor) session;
    EntityEntry ee = sessionImpl.getPersistenceContext().getEntry(target);
    if (ee == null || ee.getStatus() != Status.READ_ONLY) {
        return;
    }
    Object actualTarget = target;
    if (target instanceof HibernateProxy) {
        actualTarget = ((HibernateProxy) target).getHibernateLazyInitializer().getImplementation();
    }
    session.setReadOnly(actualTarget, false);
    session.setFlushMode(FlushMode.AUTO);
    incrementVersion(target);
}
Example 10
Project: cloudtm-data-platform-master  File: OgmEntityPersister.java View source code
@Override
public Object initializeLazyProperty(String fieldName, Object entity, SessionImplementor session) throws HibernateException {
    final Serializable id = session.getContextEntityIdentifier(entity);
    final EntityEntry entry = session.getPersistenceContext().getEntry(entity);
    if (entry == null) {
        throw new HibernateException("entity is not associated with the session: " + id);
    }
    if (log.isTraceEnabled()) {
        log.trace("initializing lazy properties of: " + MessageHelper.infoString(this, id, getFactory()) + ", field access: " + fieldName);
    }
    if (hasCache()) {
        CacheKey cacheKey = session.generateCacheKey(id, getIdentifierType(), getEntityName());
        Object ce = getCacheAccessStrategy().get(cacheKey, session.getTimestamp());
        if (ce != null) {
            CacheEntry cacheEntry = (CacheEntry) getCacheEntryStructure().destructure(ce, getFactory());
            if (!cacheEntry.areLazyPropertiesUnfetched()) {
                //note early exit here:
                return initializeLazyPropertiesFromCache(fieldName, entity, session, entry, cacheEntry);
            }
        }
    }
    return initializeLazyPropertiesFromDatastore(fieldName, entity, session, id, entry);
}