Java Code Examples for org.hibernate.proxy.LazyInitializer

The following are top voted examples for showing how to use org.hibernate.proxy.LazyInitializer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: StatefulPersistenceContext.java   View source code 6 votes vote down vote up
@Override
public boolean reassociateIfUninitializedProxy(Object value) throws MappingException {
	if ( value instanceof ElementWrapper ) {
		value = ( (ElementWrapper) value ).getElement();
	}

	if ( !Hibernate.isInitialized( value ) ) {
		final HibernateProxy proxy = (HibernateProxy) value;
		final LazyInitializer li = proxy.getHibernateLazyInitializer();
		reassociateProxy( li, proxy );
		return true;
	}
	else {
		return false;
	}
}
 
Example 2
Project: lams   File: StatefulPersistenceContext.java   View source code 6 votes vote down vote up
@Override
public Object unproxy(Object maybeProxy) throws HibernateException {
	if ( maybeProxy instanceof ElementWrapper ) {
		maybeProxy = ( (ElementWrapper) maybeProxy ).getElement();
	}

	if ( maybeProxy instanceof HibernateProxy ) {
		final HibernateProxy proxy = (HibernateProxy) maybeProxy;
		final LazyInitializer li = proxy.getHibernateLazyInitializer();
		if ( li.isUninitialized() ) {
			throw new PersistentObjectException(
					"object was an uninitialized proxy for " + li.getEntityName()
			);
		}
		//unwrap the object and return
		return li.getImplementation();
	}
	else {
		return maybeProxy;
	}
}
 
Example 3
Project: lams   File: StatefulPersistenceContext.java   View source code 6 votes vote down vote up
@Override
public Object unproxyAndReassociate(Object maybeProxy) throws HibernateException {
	if ( maybeProxy instanceof ElementWrapper ) {
		maybeProxy = ( (ElementWrapper) maybeProxy ).getElement();
	}

	if ( maybeProxy instanceof HibernateProxy ) {
		final HibernateProxy proxy = (HibernateProxy) maybeProxy;
		final LazyInitializer li = proxy.getHibernateLazyInitializer();
		reassociateProxy( li, proxy );
		//initialize + unwrap the object and return it
		return li.getImplementation();
	}
	else {
		return maybeProxy;
	}
}
 
Example 4
Project: lams   File: Hibernate.java   View source code 6 votes vote down vote up
/**
 * Check if the property is initialized. If the named property does not exist
 * or is not persistent, this method always returns <tt>true</tt>.
 *
 * @param proxy The potential proxy
 * @param propertyName the name of a persistent attribute of the object
 * @return true if the named property of the object is not listed as uninitialized; false otherwise
 */
public static boolean isPropertyInitialized(Object proxy, String propertyName) {
	final Object entity;
	if ( proxy instanceof HibernateProxy ) {
		final LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
		if ( li.isUninitialized() ) {
			return false;
		}
		else {
			entity = li.getImplementation();
		}
	}
	else {
		entity = proxy;
	}

	if ( FieldInterceptionHelper.isInstrumented( entity ) ) {
		final FieldInterceptor interceptor = FieldInterceptionHelper.extractFieldInterceptor( entity );
		return interceptor == null || interceptor.isInitialized( propertyName );
	}
	else {
		return true;
	}
}
 
Example 5
Project: lams   File: SessionImpl.java   View source code 6 votes vote down vote up
@Override
public Serializable getIdentifier(Object object) throws HibernateException {
	errorIfClosed();
	checkTransactionSynchStatus();
	if ( object instanceof HibernateProxy ) {
		LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer();
		if ( li.getSession() != this ) {
			throw new TransientObjectException( "The proxy was not associated with this session" );
		}
		return li.getIdentifier();
	}
	else {
		EntityEntry entry = persistenceContext.getEntry(object);
		if ( entry == null ) {
			throw new TransientObjectException( "The instance was not associated with this session" );
		}
		return entry.getId();
	}
}
 
Example 6
Project: lams   File: SessionImpl.java   View source code 6 votes vote down vote up
@Override
public String bestGuessEntityName(Object object) {
	if (object instanceof HibernateProxy) {
		LazyInitializer initializer = ( ( HibernateProxy ) object ).getHibernateLazyInitializer();
		// it is possible for this method to be called during flush processing,
		// so make certain that we do not accidentally initialize an uninitialized proxy
		if ( initializer.isUninitialized() ) {
			return initializer.getEntityName();
		}
		object = initializer.getImplementation();
	}
	EntityEntry entry = persistenceContext.getEntry(object);
	if (entry==null) {
		return guessEntityName(object);
	}
	else {
		return entry.getPersister().getEntityName();
	}
}
 
Example 7
Project: lams   File: DefaultLoadEventListener.java   View source code 6 votes vote down vote up
/**
 * Given a proxy, initialize it and/or narrow it provided either
 * is necessary.
 *
 * @param event The initiating load request event
 * @param persister The persister corresponding to the entity to be loaded
 * @param keyToLoad The key of the entity to be loaded
 * @param options The defined load options
 * @param persistenceContext The originating session
 * @param proxy The proxy to narrow
 *
 * @return The created/existing proxy
 */
private Object returnNarrowedProxy(
		final LoadEvent event,
		final EntityPersister persister,
		final EntityKey keyToLoad,
		final LoadEventListener.LoadType options,
		final PersistenceContext persistenceContext,
		final Object proxy) {
	LOG.trace( "Entity proxy found in session cache" );
	LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
	if ( li.isUnwrap() ) {
		return li.getImplementation();
	}
	Object impl = null;
	if ( !options.isAllowProxyCreation() ) {
		impl = load( event, persister, keyToLoad, options );
		if ( impl == null ) {
			event.getSession()
					.getFactory()
					.getEntityNotFoundDelegate()
					.handleEntityNotFound( persister.getEntityName(), keyToLoad.getIdentifier() );
		}
	}
	return persistenceContext.narrowProxy( proxy, persister, keyToLoad, impl );
}
 
Example 8
Project: cacheonix-core   File: StatefulPersistenceContext.java   View source code 6 votes vote down vote up
/**
 * Takes the given object and, if it represents a proxy, reassociates it with this event source.
 *
 * @param value The possible proxy to be reassociated.
 * @return Whether the passed value represented an actual proxy which got initialized.
 * @throws MappingException
 */
public boolean reassociateIfUninitializedProxy(Object value) throws MappingException {
	if ( value instanceof ElementWrapper ) {
		value = ( (ElementWrapper) value ).getElement();
	}
	
	if ( !Hibernate.isInitialized(value) ) {
		HibernateProxy proxy = (HibernateProxy) value;
		LazyInitializer li = proxy.getHibernateLazyInitializer();
		reassociateProxy(li, proxy);
		return true;
	}
	else {
		return false;
	}
}
 
Example 9
Project: cacheonix-core   File: StatefulPersistenceContext.java   View source code 6 votes vote down vote up
/**
 * Get the entity instance underlying the given proxy, throwing
 * an exception if the proxy is uninitialized. If the given object
 * is not a proxy, simply return the argument.
 */
public Object unproxy(Object maybeProxy) throws HibernateException {
	if ( maybeProxy instanceof ElementWrapper ) {
		maybeProxy = ( (ElementWrapper) maybeProxy ).getElement();
	}
	
	if ( maybeProxy instanceof HibernateProxy ) {
		HibernateProxy proxy = (HibernateProxy) maybeProxy;
		LazyInitializer li = proxy.getHibernateLazyInitializer();
		if ( li.isUninitialized() ) {
			throw new PersistentObjectException(
					"object was an uninitialized proxy for " +
					li.getEntityName()
			);
		}
		return li.getImplementation(); //unwrap the object
	}
	else {
		return maybeProxy;
	}
}
 
Example 10
Project: cacheonix-core   File: StatefulPersistenceContext.java   View source code 6 votes vote down vote up
/**
 * Possibly unproxy the given reference and reassociate it with the current session.
 *
 * @param maybeProxy The reference to be unproxied if it currently represents a proxy.
 * @return The unproxied instance.
 * @throws HibernateException
 */
public Object unproxyAndReassociate(Object maybeProxy) throws HibernateException {
	if ( maybeProxy instanceof ElementWrapper ) {
		maybeProxy = ( (ElementWrapper) maybeProxy ).getElement();
	}
	
	if ( maybeProxy instanceof HibernateProxy ) {
		HibernateProxy proxy = (HibernateProxy) maybeProxy;
		LazyInitializer li = proxy.getHibernateLazyInitializer();
		reassociateProxy(li, proxy);
		return li.getImplementation(); //initialize + unwrap the object
	}
	else {
		return maybeProxy;
	}
}
 
Example 11
Project: cacheonix-core   File: Hibernate.java   View source code 6 votes vote down vote up
/**
 * Check if the property is initialized. If the named property does not exist
 * or is not persistent, this method always returns <tt>true</tt>.
 *
 * @param proxy The potential proxy
 * @param propertyName the name of a persistent attribute of the object
 * @return true if the named property of the object is not listed as uninitialized
 * @return false if the object is an uninitialized proxy, or the named property is uninitialized
 */
public static boolean isPropertyInitialized(Object proxy, String propertyName) {
	
	Object entity;
	if ( proxy instanceof HibernateProxy ) {
		LazyInitializer li = ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer();
		if ( li.isUninitialized() ) {
			return false;
		}
		else {
			entity = li.getImplementation();
		}
	}
	else {
		entity = proxy;
	}

	if ( FieldInterceptionHelper.isInstrumented( entity ) ) {
		FieldInterceptor interceptor = FieldInterceptionHelper.extractFieldInterceptor( entity );
		return interceptor == null || interceptor.isInitialized( propertyName );
	}
	else {
		return true;
	}
	
}
 
Example 12
Project: cacheonix-core   File: DefaultLoadEventListener.java   View source code 6 votes vote down vote up
/**
 * Given that there is a pre-existing proxy.
 * Initialize it if necessary; narrow if necessary.
 */
private Object returnNarrowedProxy(
		final LoadEvent event, 
		final EntityPersister persister, 
		final EntityKey keyToLoad, 
		final LoadEventListener.LoadType options, 
		final PersistenceContext persistenceContext, 
		final Object proxy
) {
	log.trace("entity proxy found in session cache");
	LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
	if ( li.isUnwrap() ) {
		return li.getImplementation();
	}
	Object impl = null;
	if ( !options.isAllowProxyCreation() ) {
		impl = load( event, persister, keyToLoad, options );
		if ( impl == null ) {
			event.getSession().getFactory().getEntityNotFoundDelegate().handleEntityNotFound( persister.getEntityName(), keyToLoad.getIdentifier());
		}
	}
	return persistenceContext.narrowProxy( proxy, persister, keyToLoad, impl );
}
 
Example 13
Project: cacheonix-core   File: SessionImpl.java   View source code 6 votes vote down vote up
public Serializable getIdentifier(Object object) throws HibernateException {
	errorIfClosed();
	checkTransactionSynchStatus();
	if ( object instanceof HibernateProxy ) {
		LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer();
		if ( li.getSession() != this ) {
			throw new TransientObjectException( "The proxy was not associated with this session" );
		}
		return li.getIdentifier();
	}
	else {
		EntityEntry entry = persistenceContext.getEntry(object);
		if ( entry == null ) {
			throw new TransientObjectException( "The instance was not associated with this session" );
		}
		return entry.getId();
	}
}
 
Example 14
Project: cacheonix-core   File: SessionImpl.java   View source code 6 votes vote down vote up
public String bestGuessEntityName(Object object) {
	if (object instanceof HibernateProxy) {
		LazyInitializer initializer = ( ( HibernateProxy ) object ).getHibernateLazyInitializer();
		// it is possible for this method to be called during flush processing,
		// so make certain that we do not accidently initialize an uninitialized proxy
		if ( initializer.isUninitialized() ) {
			return initializer.getEntityName();
		}
		object = initializer.getImplementation();
	}
	EntityEntry entry = persistenceContext.getEntry(object);
	if (entry==null) {
		return guessEntityName(object);
	}
	else {
		return entry.getPersister().getEntityName();
	}
}
 
Example 15
Project: eMonocot   File: DaoImpl.java   View source code 6 votes vote down vote up
/**
 *
 * @param o Set the object
 * @param association Set the association to initialize
 */
protected Object initializeProperty(final Object o, final String association) {
	Object object;
	try {
		object = PropertyUtils.getProperty(o, association);
	} catch (Exception e) {
		logger.debug("Cannot get proxy " + association + " for class " + o.getClass());
		return null;
	}
	if (object == null) {
		return null;
	} else if (object instanceof HibernateProxy) {
		((HibernateProxy) object).getHibernateLazyInitializer().initialize();
		LazyInitializer lazyInitializer = ((HibernateProxy) object)
				.getHibernateLazyInitializer();
		return lazyInitializer.getImplementation();
	} else if (object instanceof PersistentCollection) {
		((PersistentCollection) object).forceInitialization();
		return object;
	} else {
		return object;
	}
}
 
Example 16
Project: powop   File: DaoImpl.java   View source code 6 votes vote down vote up
/**
 *
 * @param o Set the object
 * @param association Set the association to initialize
 */
protected Object initializeProperty(final Object o, final String association) {
	Object object;
	try {
		object = PropertyUtils.getProperty(o, association);
	} catch (Exception e) {
		logger.debug("Cannot get proxy " + association + " for class " + o.getClass());
		return null;
	}
	if (object == null) {
		return null;
	} else if (object instanceof HibernateProxy) {
		logger.debug("Initializing {}.{}", object.getClass().getName(), association);
		((HibernateProxy) object).getHibernateLazyInitializer().initialize();
		LazyInitializer lazyInitializer = ((HibernateProxy) object).getHibernateLazyInitializer();
		return lazyInitializer.getImplementation();
	} else if (object instanceof PersistentCollection) {
		((PersistentCollection) object).forceInitialization();
		return object;
	} else {
		return object;
	}
}
 
Example 17
Project: jspresso-ce   File: JspressoMongoEventListener.java   View source code 6 votes vote down vote up
/**
 * Gets entity.
 *
 * @param entityName
 *     the entity name
 * @param id
 *     the id
 * @return the entity
 */
@SuppressWarnings("unchecked")
protected IEntity getEntity(String entityName, Serializable id) {
  IEntity registeredEntity = null;
  try {
    if (getBackendController().isUnitOfWorkActive()) {
      registeredEntity = getBackendController().getUnitOfWorkEntity((Class<? extends IEntity>) Class.forName(
          entityName), id);
    } else {
      registeredEntity = getBackendController().getRegisteredEntity((Class<? extends IEntity>) Class.forName(
          entityName), id);
      if (registeredEntity instanceof HibernateProxy) {
        HibernateProxy proxy = (HibernateProxy) registeredEntity;
        LazyInitializer li = proxy.getHibernateLazyInitializer();
        registeredEntity = (IEntity) li.getImplementation();
      }
    }
  } catch (ClassNotFoundException ex) {
    LOG.error("Class for entity {} was not found", entityName, ex);
  }
  return registeredEntity;
}
 
Example 18
Project: breeze.server.java   File: HibernateProxyTypeAdapter.java   View source code 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
  @Override
  public void write(JsonWriter out, HibernateProxy value) throws IOException {
      if (value == null) {
          out.nullValue();
          return;
      }

LazyInitializer initializer =  value.getHibernateLazyInitializer();
if (initializer.isUninitialized()) {
	out.nullValue();
	return;
} else {
       // Retrieve the original (not proxy) class
       Class<?> baseType = Hibernate.getClass(value);
       // Get the TypeAdapter of the original class, to delegate the serialization
       TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));
       // Get a filled instance of the original class
       Object unproxiedValue = initializer.getImplementation();
       // Serialize the value
       delegate.write(out, unproxiedValue);
}
  }
 
Example 19
Project: lams   File: StatefulPersistenceContext.java   View source code 5 votes vote down vote up
@Override
public void reassociateProxy(Object value, Serializable id) throws MappingException {
	if ( value instanceof ElementWrapper ) {
		value = ( (ElementWrapper) value ).getElement();
	}

	if ( value instanceof HibernateProxy ) {
		LOG.debugf( "Setting proxy identifier: %s", id );
		final HibernateProxy proxy = (HibernateProxy) value;
		final LazyInitializer li = proxy.getHibernateLazyInitializer();
		li.setIdentifier( id );
		reassociateProxy( li, proxy );
	}
}
 
Example 20
Project: lams   File: StatefulPersistenceContext.java   View source code 5 votes vote down vote up
/**
 * Associate a proxy that was instantiated by another session with this session
 *
 * @param li The proxy initializer.
 * @param proxy The proxy to reassociate.
 */
private void reassociateProxy(LazyInitializer li, HibernateProxy proxy) {
	if ( li.getSession() != this.getSession() ) {
		final EntityPersister persister = session.getFactory().getEntityPersister( li.getEntityName() );
		final EntityKey key = session.generateEntityKey( li.getIdentifier(), persister );
	  	// any earlier proxy takes precedence
		proxiesByKey.putIfAbsent( key, proxy );
		proxy.getHibernateLazyInitializer().setSession( session );
	}
}
 
Example 21
Project: lams   File: SessionImpl.java   View source code 5 votes vote down vote up
@Override
public boolean contains(Object object) {
	errorIfClosed();
	checkTransactionSynchStatus();
	if ( object instanceof HibernateProxy ) {
		//do not use proxiesByKey, since not all
		//proxies that point to this session's
		//instances are in that collection!
		LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer();
		if ( li.isUninitialized() ) {
			//if it is an uninitialized proxy, pointing
			//with this session, then when it is accessed,
			//the underlying instance will be "contained"
			return li.getSession()==this;
		}
		else {
			//if it is initialized, see if the underlying
			//instance is contained, since we need to
			//account for the fact that it might have been
			//evicted
			object = li.getImplementation();
		}
	}
	// A session is considered to contain an entity only if the entity has
	// an entry in the session's persistence context and the entry reports
	// that the entity has not been removed
	EntityEntry entry = persistenceContext.getEntry( object );
	delayedAfterCompletion();
	return entry != null && entry.getStatus() != Status.DELETED && entry.getStatus() != Status.GONE;
}
 
Example 22
Project: lams   File: FieldInterceptorImpl.java   View source code 5 votes vote down vote up
@Override
public Object readObject(Object target, String name, Object oldValue) {
	Object value = intercept( target, name, oldValue );
	if ( value instanceof HibernateProxy ) {
		final LazyInitializer li = ( (HibernateProxy) value ).getHibernateLazyInitializer();
		if ( li.isUnwrap() ) {
			value = li.getImplementation();
		}
	}
	return value;
}
 
Example 23
Project: lams   File: AnyType.java   View source code 5 votes vote down vote up
private EntityPersister guessEntityPersister(Object object) {
	if ( scope == null ) {
		return null;
	}

	String entityName = null;

	// this code is largely copied from Session's bestGuessEntityName
	Object entity = object;
	if ( entity instanceof HibernateProxy ) {
		final LazyInitializer initializer = ( (HibernateProxy) entity ).getHibernateLazyInitializer();
		if ( initializer.isUninitialized() ) {
			entityName = initializer.getEntityName();
		}
		entity = initializer.getImplementation();
	}

	if ( entityName == null ) {
		for ( EntityNameResolver resolver : scope.resolveFactory().iterateEntityNameResolvers() ) {
			entityName = resolver.resolveEntityName( entity );
			if ( entityName != null ) {
				break;
			}
		}
	}

	if ( entityName == null ) {
		// the old-time stand-by...
		entityName = object.getClass().getName();
	}

	return scope.resolveFactory().getEntityPersister( entityName );
}
 
Example 24
Project: lams   File: CollectionType.java   View source code 5 votes vote down vote up
public boolean contains(Object collection, Object childObject, SessionImplementor session) {
	// we do not have to worry about queued additions to uninitialized
	// collections, since they can only occur for inverse collections!
	Iterator elems = getElementsIterator( collection, session );
	while ( elems.hasNext() ) {
		Object element = elems.next();
		// worrying about proxies is perhaps a little bit of overkill here...
		if ( element instanceof HibernateProxy ) {
			LazyInitializer li = ( (HibernateProxy) element ).getHibernateLazyInitializer();
			if ( !li.isUninitialized() ) element = li.getImplementation();
		}
		if ( element == childObject ) return true;
	}
	return false;
}
 
Example 25
Project: parabuild-ci   File: H3BeanConverter.java   View source code 5 votes vote down vote up
/**
 * Hibernate makes {@link Class#getClass()} diffficult ...
 * @param example The class that we want to call {@link Class#getClass()} on
 * @return The type of the given object
 */
public Class getClass(Object example)
{
    if (example instanceof HibernateProxy)
    {
        HibernateProxy proxy = (HibernateProxy) example;
        LazyInitializer initializer = proxy.getHibernateLazyInitializer();
        SessionImplementor implementor = initializer.getSession();

        if (initializer.isUninitialized())
        {
            try
            {
                // getImplementation is going to want to talk to a session
                if (implementor.isClosed())
                {
                    // Give up and return example.getClass();
                    return example.getClass();
                }
            }
            catch (NoSuchMethodError ex)
            {
                // We must be using Hibernate 3.0/3.1 which doesn't have
                // this method
            }
        }

        return initializer.getImplementation().getClass();
    }
    else
    {
        return example.getClass();
    }
}
 
Example 26
Project: dwr   File: H3BeanConverter.java   View source code 5 votes vote down vote up
/**
 * Hibernate makes {@link Class#getClass()} difficult ...
 * @param example The class that we want to call {@link Class#getClass()} on
 * @return The type of the given object
 */
public Class<?> getClass(Object example)
{
    if (example instanceof HibernateProxy)
    {
        HibernateProxy proxy = (HibernateProxy) example;
        LazyInitializer initializer = proxy.getHibernateLazyInitializer();
        SessionImplementor implementor = initializer.getSession();

        if (initializer.isUninitialized())
        {
            try
            {
                // getImplementation is going to want to talk to a session
                if (implementor.isClosed())
                {
                    // Give up and return example.getClass();
                    return example.getClass();
                }
            }
            catch (NoSuchMethodError ex)
            {
                // We must be using Hibernate 3.0/3.1 which doesn't have
                // this method
            }
        }

        return initializer.getImplementation().getClass();
    }
    else
    {
        return example.getClass();
    }
}
 
Example 27
Project: dwr   File: H4BeanConverter.java   View source code 5 votes vote down vote up
/**
 * Hibernate makes {@link Class#getClass()} difficult ...
 * @param example The class that we want to call {@link Class#getClass()} on
 * @return The type of the given object
 */
public Class<?> getClass(Object example)
{
    if (example instanceof HibernateProxy)
    {
        HibernateProxy proxy = (HibernateProxy) example;
        LazyInitializer initializer = proxy.getHibernateLazyInitializer();
        SessionImplementor implementor = initializer.getSession();

        if (initializer.isUninitialized())
        {
            try
            {
                // getImplementation is going to want to talk to a session
                if (implementor.isClosed())
                {
                    // Give up and return example.getClass();
                    return example.getClass();
                }
            }
            catch (NoSuchMethodError ex)
            {
                // We must be using Hibernate 3.0/3.1 which doesn't have
                // this method
            }
        }

        return initializer.getImplementation().getClass();
    }
    else
    {
        return example.getClass();
    }
}
 
Example 28
Project: CredentialStorageService-dw-hibernate   File: AbstractDAOTest.java   View source code 5 votes vote down vote up
@Test
public void initializesProxies() throws Exception {
    final LazyInitializer initializer = mock(LazyInitializer.class);
    when(initializer.isUninitialized()).thenReturn(true);
    final HibernateProxy proxy = mock(HibernateProxy.class);
    when(proxy.getHibernateLazyInitializer()).thenReturn(initializer);

    this.dao.initialize(proxy);

    verify(initializer).initialize();
}
 
Example 29
Project: jpasecurity   File: SecurePersistenceUnitUtil.java   View source code 5 votes vote down vote up
@Override
public Object getIdentifier(Object entity) {
    if (entity instanceof org.hibernate.proxy.HibernateProxy) {
        LazyInitializer initializer
            = ((org.hibernate.proxy.HibernateProxy)entity).getHibernateLazyInitializer();
        return initializer.getIdentifier();
    } else {
        return persistenceUnitUtil.getIdentifier(entity);
    }
}
 
Example 30
Project: jpasecurity   File: SecurePersistenceUnitUtil.java   View source code 5 votes vote down vote up
@Override
public <T> T unproxy(T proxy) {
    if (proxy instanceof org.hibernate.proxy.HibernateProxy) {
        LazyInitializer initializer
            = ((org.hibernate.proxy.HibernateProxy)proxy).getHibernateLazyInitializer();
        return (T)initializer.getImplementation();
    } else {
        return proxy;
    }
}
 
Example 31
Project: cacheonix-core   File: StatefulPersistenceContext.java   View source code 5 votes vote down vote up
public void clear() {
	Iterator itr = proxiesByKey.values().iterator();
	while ( itr.hasNext() ) {
		final LazyInitializer li = ( ( HibernateProxy ) itr.next() ).getHibernateLazyInitializer();
		li.setSession( null );
	}
	Map.Entry[] collectionEntryArray = IdentityMap.concurrentEntries( collectionEntries );
	for ( int i = 0; i < collectionEntryArray.length; i++ ) {
		( ( PersistentCollection ) collectionEntryArray[i].getKey() ).unsetSession( getSession() );
	}
	arrayHolders.clear();
	entitiesByKey.clear();
	entitiesByUniqueKey.clear();
	entityEntries.clear();
	entitySnapshotsByKey.clear();
	collectionsByKey.clear();
	collectionEntries.clear();
	if ( unownedCollections != null ) {
		unownedCollections.clear();
	}
	proxiesByKey.clear();
	nullifiableEntityKeys.clear();
	if ( batchFetchQueue != null ) {
		batchFetchQueue.clear();
	}
	hasNonReadOnlyEntities = false;
	if ( loadContexts != null ) {
		loadContexts.cleanup();
	}
}
 
Example 32
Project: cacheonix-core   File: StatefulPersistenceContext.java   View source code 5 votes vote down vote up
/**
 * If a deleted entity instance is re-saved, and it has a proxy, we need to
 * reset the identifier of the proxy 
 */
public void reassociateProxy(Object value, Serializable id) throws MappingException {
	if ( value instanceof ElementWrapper ) {
		value = ( (ElementWrapper) value ).getElement();
	}
	
	if ( value instanceof HibernateProxy ) {
		if ( log.isDebugEnabled() ) log.debug("setting proxy identifier: " + id);
		HibernateProxy proxy = (HibernateProxy) value;
		LazyInitializer li = proxy.getHibernateLazyInitializer();
		li.setIdentifier(id);
		reassociateProxy(li, proxy);
	}
}
 
Example 33
Project: cacheonix-core   File: StatefulPersistenceContext.java   View source code 5 votes vote down vote up
/**
 * Associate a proxy that was instantiated by another session with this session
 *
 * @param li The proxy initializer.
 * @param proxy The proxy to reassociate.
 */
private void reassociateProxy(LazyInitializer li, HibernateProxy proxy) {
	if ( li.getSession() != this.getSession() ) {
		EntityPersister persister = session.getFactory().getEntityPersister( li.getEntityName() );
		EntityKey key = new EntityKey( li.getIdentifier(), persister, session.getEntityMode() );
	  	// any earlier proxy takes precedence
		if ( !proxiesByKey.containsKey( key ) ) {
			proxiesByKey.put( key, proxy );
		}
		proxy.getHibernateLazyInitializer().setSession( session );
	}
}
 
Example 34
Project: cacheonix-core   File: StatefulPersistenceContext.java   View source code 5 votes vote down vote up
/**
 * If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy
 * and overwrite the registration of the old one. This breaks == and occurs only for
 * "class" proxies rather than "interface" proxies. Also init the proxy to point to
 * the given target implementation if necessary.
 *
 * @param proxy The proxy instance to be narrowed.
 * @param persister The persister for the proxied entity.
 * @param key The internal cache key for the proxied entity.
 * @param object (optional) the actual proxied entity instance.
 * @return An appropriately narrowed instance.
 * @throws HibernateException
 */
public Object narrowProxy(Object proxy, EntityPersister persister, EntityKey key, Object object)
throws HibernateException {
	
	boolean alreadyNarrow = persister.getConcreteProxyClass( session.getEntityMode() )
			.isAssignableFrom( proxy.getClass() );
	
	if ( !alreadyNarrow ) {
		if ( PROXY_WARN_LOG.isWarnEnabled() ) {
			PROXY_WARN_LOG.warn(
					"Narrowing proxy to " +
					persister.getConcreteProxyClass( session.getEntityMode() ) +
					" - this operation breaks =="
			);
		}

		if ( object != null ) {
			proxiesByKey.remove(key);
			return object; //return the proxied object
		}
		else {
			proxy = persister.createProxy( key.getIdentifier(), session );
			proxiesByKey.put(key, proxy); //overwrite old proxy
			return proxy;
		}
		
	}
	else {
		
		if ( object != null ) {
			LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
			li.setImplementation(object);
		}
		
		return proxy;
		
	}
	
}
 
Example 35
Project: cacheonix-core   File: FieldInterceptorImpl.java   View source code 5 votes vote down vote up
public Object readObject(Object target, String name, Object oldValue) {
	Object value = intercept( target, name, oldValue );
	if (value instanceof HibernateProxy) {
		LazyInitializer li = ( (HibernateProxy) value ).getHibernateLazyInitializer();
		if ( li.isUnwrap() ) {
			value = li.getImplementation();
		}
	}
	return value;
}
 
Example 36
Project: cacheonix-core   File: FieldInterceptorImpl.java   View source code 5 votes vote down vote up
public Object readObject(Object target, String name, Object oldValue) {
	Object value = intercept( target, name, oldValue );
	if (value instanceof HibernateProxy) {
		LazyInitializer li = ( (HibernateProxy) value ).getHibernateLazyInitializer();
		if ( li.isUnwrap() ) {
			value = li.getImplementation();
		}
	}
	return value;
}
 
Example 37
Project: cacheonix-core   File: SessionImpl.java   View source code 5 votes vote down vote up
public boolean contains(Object object) {
	errorIfClosed();
	checkTransactionSynchStatus();
	if ( object instanceof HibernateProxy ) {
		//do not use proxiesByKey, since not all
		//proxies that point to this session's
		//instances are in that collection!
		LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer();
		if ( li.isUninitialized() ) {
			//if it is an uninitialized proxy, pointing
			//with this session, then when it is accessed,
			//the underlying instance will be "contained"
			return li.getSession()==this;
		}
		else {
			//if it is initialized, see if the underlying
			//instance is contained, since we need to 
			//account for the fact that it might have been
			//evicted
			object = li.getImplementation();
		}
	}
	// A session is considered to contain an entity only if the entity has
	// an entry in the session's persistence context and the entry reports
	// that the entity has not been removed
	EntityEntry entry = persistenceContext.getEntry( object );
	return entry != null && entry.getStatus() != Status.DELETED && entry.getStatus() != Status.GONE;
}
 
Example 38
Project: cacheonix-core   File: CollectionType.java   View source code 5 votes vote down vote up
public boolean contains(Object collection, Object childObject, SessionImplementor session) {
	// we do not have to worry about queued additions to uninitialized
	// collections, since they can only occur for inverse collections!
	Iterator elems = getElementsIterator( collection, session );
	while ( elems.hasNext() ) {
		Object element = elems.next();
		// worrying about proxies is perhaps a little bit of overkill here...
		if ( element instanceof HibernateProxy ) {
			LazyInitializer li = ( (HibernateProxy) element ).getHibernateLazyInitializer();
			if ( !li.isUninitialized() ) element = li.getImplementation();
		}
		if ( element == childObject ) return true;
	}
	return false;
}
 
Example 39
Project: cacheonix-core   File: EntityType.java   View source code 5 votes vote down vote up
/**
 * Get the identifier value of an instance or proxy.
 * <p/>
 * Intended only for loggin purposes!!!
 *
 * @param object The object from which to extract the identifier.
 * @param persister The entity persister
 * @param entityMode The entity mode
 * @return The extracted identifier.
 */
private static Serializable getIdentifier(Object object, EntityPersister persister, EntityMode entityMode) {
	if (object instanceof HibernateProxy) {
		HibernateProxy proxy = (HibernateProxy) object;
		LazyInitializer li = proxy.getHibernateLazyInitializer();
		return li.getIdentifier();
	}
	else {
		return persister.getIdentifier( object, entityMode );
	}
}
 
Example 40
Project: eMonocot   File: HibernateProxySerializer.java   View source code 5 votes vote down vote up
/**
 * Helper method for finding value being proxied, if it is available
 * or if it is to be forced to be loaded.
 */
protected Object findProxied(HibernateProxy proxy)
{
	LazyInitializer init = proxy.getHibernateLazyInitializer();
	if (!_forceLazyLoading && init.isUninitialized()) {
		return null;
	}
	return init.getImplementation();
}