Java Code Examples for org.hibernate.proxy.HibernateProxy

The following are top voted examples for showing how to use org.hibernate.proxy.HibernateProxy. 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: oscm   File: EJBTestBase.java   View source code 6 votes vote down vote up
protected <T> T unproxyEntity(T template) {
    if (template instanceof HibernateProxy) {
        Hibernate.initialize(template);
        template = (T) ((HibernateProxy) template)
                .getHibernateLazyInitializer()
                .getImplementation();
    }
    return template;
}
 
Example 2
Project: lams   File: EntityReturnReader.java   View source code 6 votes vote down vote up
@Override
public Object read(ResultSet resultSet, ResultSetProcessingContext context) throws SQLException {
	final EntityReferenceProcessingState processingState = getIdentifierResolutionContext( context );

	final EntityKey entityKey = processingState.getEntityKey();
	final Object entityInstance = context.getProcessingState( entityReturn ).getEntityInstance();

	if ( context.shouldReturnProxies() ) {
		final Object proxy = context.getSession().getPersistenceContext().proxyFor(
				entityReturn.getEntityPersister(),
				entityKey,
				entityInstance
		);
		if ( proxy != entityInstance ) {
			( (HibernateProxy) proxy ).getHibernateLazyInitializer().setImplementation( proxy );
			return proxy;
		}
	}

	return entityInstance;
}
 
Example 3
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 4
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 5
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 6
Project: lams   File: JavassistProxyFactory.java   View source code 6 votes vote down vote up
@Override
public HibernateProxy getProxy(
		Serializable id,
		SessionImplementor session) throws HibernateException {
	return JavassistLazyInitializer.getProxy(
			factory,
			entityName,
			persistentClass,
			interfaces,
			getIdentifierMethod,
			setIdentifierMethod,
			componentIdType,
			id,
			session,
			overridesEquals
	);
}
 
Example 7
Project: lams   File: SerializableProxy.java   View source code 6 votes vote down vote up
private Object readResolve() {
	try {
		HibernateProxy proxy = JavassistLazyInitializer.getProxy(
			getEntityName(),
			persistentClass,
			interfaces,
			getIdentifierMethodName==null
					? null
					: getIdentifierMethodClass.getDeclaredMethod( getIdentifierMethodName, (Class[]) null ),
			setIdentifierMethodName==null
					? null 
					: setIdentifierMethodClass.getDeclaredMethod(setIdentifierMethodName, setIdentifierMethodParams),
			componentIdType,
			getId(),
			null
		);
		setReadOnlyBeforeAttachedToSession( ( JavassistLazyInitializer ) proxy.getHibernateLazyInitializer() );
		return proxy;
	}
	catch (NoSuchMethodException nsme) {
		throw new HibernateException("could not create proxy for entity: " + getEntityName(), nsme);
	}
}
 
Example 8
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 9
Project: lams   File: SessionImpl.java   View source code 6 votes vote down vote up
@Override
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 10
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 11
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 12
Project: lams   File: SessionImpl.java   View source code 6 votes vote down vote up
@Override
public String getEntityName(Object object) {
	errorIfClosed();
	checkTransactionSynchStatus();
	if (object instanceof HibernateProxy) {
		if ( !persistenceContext.containsProxy( object ) ) {
			throw new TransientObjectException("proxy was not associated with the session");
		}
		object = ( (HibernateProxy) object ).getHibernateLazyInitializer().getImplementation();
	}

	EntityEntry entry = persistenceContext.getEntry(object);
	if ( entry == null ) {
		throwTransientObjectException( object );
	}
	return entry.getPersister().getEntityName();
}
 
Example 13
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 14
Project: lams   File: EntityType.java   View source code 6 votes vote down vote up
/**
 * Resolve an identifier via a load.
 *
 * @param id The entity id to resolve
 * @param session The orginating session.
 * @return The resolved identifier (i.e., loaded entity).
 * @throws org.hibernate.HibernateException Indicates problems performing the load.
 */
protected final Object resolveIdentifier(Serializable id, SessionImplementor session) throws HibernateException {
	boolean isProxyUnwrapEnabled = unwrapProxy &&
			getAssociatedEntityPersister( session.getFactory() )
					.isInstrumented();

	Object proxyOrEntity = session.internalLoad(
			getAssociatedEntityName(),
			id,
			eager,
			isNullable() && !isProxyUnwrapEnabled
	);

	if ( proxyOrEntity instanceof HibernateProxy ) {
		( ( HibernateProxy ) proxyOrEntity ).getHibernateLazyInitializer()
				.setUnwrap( isProxyUnwrapEnabled );
	}

	return proxyOrEntity;
}
 
Example 15
Project: gitplex-mit   File: HibernateProxySerializer.java   View source code 6 votes vote down vote up
@Override
public void serializeWithType(HibernateProxy value, JsonGenerator jgen,
		SerializerProvider provider, TypeSerializer typeSer)
		throws IOException, JsonProcessingException {
	Object proxiedValue = findProxied(value);
	if (proxiedValue == null) {
		provider.defaultSerializeNull(jgen);
		return;
	}
	/*
	 * This isn't exactly right, since type serializer really refers to
	 * proxy object, not value. And we really don't either know static type
	 * (necessary to know how to apply additional type info) or other
	 * things; so it's not going to work well. But... we'll do out best.
	 */
	findSerializer(provider, proxiedValue).serializeWithType(proxiedValue,
			jgen, provider, typeSer);
}
 
Example 16
Project: java-a-to-z   File: User.java   View source code 6 votes vote down vote up
public List<Ad> getAdList() {
    List<Ad> result = null;
    if (this.adList != null && this.adList.size() != 0) {
        result = new ArrayList<>();
        for (Ad ad : adList) {
            if (ad instanceof HibernateProxy) {
                Hibernate.initialize(ad);
                ad = (Ad) ((HibernateProxy) ad)
                        .getHibernateLazyInitializer()
                        .getImplementation();
                result.add(ad);
            }
        }
    }
    return result;
}
 
Example 17
Project: java-a-to-z   File: User.java   View source code 6 votes vote down vote up
public List<Ad> getAdList() {
    List<Ad> result = null;
    if (this.adList != null && this.adList.size() != 0) {
        result = new ArrayList<>();
        for (Ad ad : adList) {
            if (ad instanceof HibernateProxy) {
                Hibernate.initialize(ad);
                ad = (Ad) ((HibernateProxy) ad)
                        .getHibernateLazyInitializer()
                        .getImplementation();
                result.add(ad);
            }
        }
    }
    return result;
}
 
Example 18
Project: openbravo-brazil   File: DalUtil.java   View source code 6 votes vote down vote up
/**
 * Is used when the value of the foreign-key column should be retrieved. In java the value of a
 * reference is an entity. This method is usefull to get to the actual database foreign key value
 * (often the primary key of the referenced object). This method has a special implementation to
 * prevent unwanted loading of Hibernate Proxies. This loading is not required if only the id of
 * the referenced object needs to be returned.
 * 
 * @param referencingProperty
 *          the property which models the association, it is a property of the refering object
 *          (the owner)
 * @param referedObject
 *          the entity to which is being refered
 * @return the id of the referedObject (most of the time) or if the foreign key is to another
 *         property then the value of that property is returned
 */
public static Serializable getReferencedPropertyValue(Property referencingProperty,
    Object referedObject) {
  Check.isTrue(referencingProperty.getReferencedProperty() != null, "This property "
      + referencingProperty + " does not have a referenced Property");
  final Property referencedProperty = referencingProperty.getReferencedProperty();
  if (referencedProperty.isId()) {
    if (referedObject instanceof HibernateProxy)
      return ((HibernateProxy) referedObject).getHibernateLazyInitializer().getIdentifier();
    if (referedObject instanceof BaseOBObject)
      return (Serializable) ((BaseOBObject) referedObject).getId();
  } else if (referedObject instanceof BaseOBObject) {
    return (Serializable) ((BaseOBObject) referedObject).get(referencedProperty.getName());
  }

  throw new ArgumentException("Argument is not a BaseOBObject and not a HibernateProxy");
}
 
Example 19
Project: gorm-hibernate5   File: GrailsHibernateUtil.java   View source code 6 votes vote down vote up
/**
 * 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 20
Project: cacheonix-core   File: Dom4jEntityTuplizer.java   View source code 6 votes vote down vote up
protected ProxyFactory buildProxyFactory(PersistentClass mappingInfo, Getter idGetter, Setter idSetter) {
	HashSet proxyInterfaces = new HashSet();
	proxyInterfaces.add( HibernateProxy.class );
	proxyInterfaces.add( Element.class );

	ProxyFactory pf = new Dom4jProxyFactory();
	try {
		pf.postInstantiate(
				getEntityName(),
				Element.class,
				proxyInterfaces,
				null,
				null,
				mappingInfo.hasEmbeddedIdentifier() ?
		                (AbstractComponentType) mappingInfo.getIdentifier().getType() :
		                null
		);
	}
	catch ( HibernateException he ) {
		log.warn( "could not create proxy factory for:" + getEntityName(), he );
		pf = null;
	}
	return pf;
}
 
Example 21
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 22
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 23
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 24
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 25
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 26
Project: cacheonix-core   File: SessionImpl.java   View source code 6 votes vote down vote up
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 27
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 28
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 29
Project: cacheonix-core   File: SessionImpl.java   View source code 6 votes vote down vote up
public String getEntityName(Object object) {
	errorIfClosed();
	checkTransactionSynchStatus();
	if (object instanceof HibernateProxy) {
		if ( !persistenceContext.containsProxy( object ) ) {
			throw new TransientObjectException("proxy was not associated with the session");
		}
		object = ( (HibernateProxy) object ).getHibernateLazyInitializer().getImplementation();
	}

	EntityEntry entry = persistenceContext.getEntry(object);
	if ( entry == null ) {
		throwTransientObjectException( object );
	}
	return entry.getPersister().getEntityName();
}
 
Example 30
Project: cacheonix-core   File: EntityType.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public int getHashCode(Object x, EntityMode entityMode, SessionFactoryImplementor factory) {
	EntityPersister persister = factory.getEntityPersister(associatedEntityName);
	if ( !persister.canExtractIdOutOfEntity() ) {
		return super.getHashCode(x, entityMode);
	}

	final Serializable id;
	if (x instanceof HibernateProxy) {
		id = ( (HibernateProxy) x ).getHibernateLazyInitializer().getIdentifier();
	}
	else {
		id = persister.getIdentifier(x, entityMode);
	}
	return persister.getIdentifierType().getHashCode(id, entityMode, factory);
}
 
Example 31
Project: cacheonix-core   File: EntityType.java   View source code 6 votes vote down vote up
/**
 * Resolve an identifier via a load.
 *
 * @param id The entity id to resolve
 * @param session The orginating session.
 * @return The resolved identifier (i.e., loaded entity).
 * @throws org.hibernate.HibernateException Indicates problems performing the load.
 */
protected final Object resolveIdentifier(Serializable id, SessionImplementor session) throws HibernateException {
	boolean isProxyUnwrapEnabled = unwrapProxy &&
			session.getFactory()
					.getEntityPersister( getAssociatedEntityName() )
					.isInstrumented( session.getEntityMode() );

	Object proxyOrEntity = session.internalLoad(
			getAssociatedEntityName(),
			id,
			eager,
			isNullable() && !isProxyUnwrapEnabled
	);

	if ( proxyOrEntity instanceof HibernateProxy ) {
		( ( HibernateProxy ) proxyOrEntity ).getHibernateLazyInitializer()
				.setUnwrap( isProxyUnwrapEnabled );
	}

	return proxyOrEntity;
}
 
Example 32
Project: WechatTicketSystem   File: SQLCore.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;
    }
    // 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 = ((HibernateProxy) value).getHibernateLazyInitializer()
            .getImplementation();
    // Serialize the value
    delegate.write(out, unproxiedValue);
}
 
Example 33
Project: Translation   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;
	}
	// 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 = ((HibernateProxy) value).getHibernateLazyInitializer()
			.getImplementation();
	// Serialize the value
	delegate.write(out, unproxiedValue);
}
 
Example 34
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 35
Project: eMonocot   File: HibernateSerializers.java   View source code 6 votes vote down vote up
@Override
public JsonSerializer<?> findSerializer(
		SerializationConfig config, JavaType type,
		BeanDescription beanDesc)
		{
	Class<?> raw = type.getRawClass();

	/* Note: PersistentCollection does not implement Collection, so we
	 * may get some types here...
	 */
	if (PersistentCollection.class.isAssignableFrom(raw)) {
		// TODO: handle iterator types? Or PersistentArrayHolder?
	}

	if (HibernateProxy.class.isAssignableFrom(raw)) {
		return new HibernateProxySerializer(isEnabled(Feature.FORCE_LAZY_LOADING));
	}
	return null;
		}
 
Example 36
Project: eMonocot   File: HibernateProxySerializer.java   View source code 6 votes vote down vote up
public void serializeWithType(HibernateProxy value, JsonGenerator jgen, SerializerProvider provider,
		TypeSerializer typeSer)
				throws IOException, JsonProcessingException
{
	Object proxiedValue = findProxied(value);
	if (proxiedValue == null) {
		provider.defaultSerializeNull(jgen);
		return;
	}
	/* This isn't exactly right, since type serializer really refers to proxy
	 * object, not value. And we really don't either know static type (necessary
	 * to know how to apply additional type info) or other things;
	 * so it's not going to work well. But... we'll do out best.
	 */
	findSerializer(provider, proxiedValue).serializeWithType(proxiedValue, jgen, provider, typeSer);
}
 
Example 37
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 38
Project: cia   File: LoadHelper.java   View source code 6 votes vote down vote up
/**
 * Recursive initliaze.
 *
 * @param obj
 *            the obj
 * @param dejaVu
 *            the deja vu
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws NoSuchMethodException
 *             the no such method exception
 */
private static void recursiveInitialize(final Object obj, final Set<Object> dejaVu)
		throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
	if (dejaVu.contains(obj)) {
		return;
	} else {
		dejaVu.add(obj);

		if (!Hibernate.isInitialized(obj)) {
			Hibernate.initialize(obj);
		}

		if (obj instanceof HibernateProxy || obj instanceof PersistentCollection) {

			initProxyAndCollections(obj, PropertyUtils.getPropertyDescriptors(obj), dejaVu);
		}
	}
}
 
Example 39
Project: cmdit   File: HibernateProxyUtils.java   View source code 6 votes vote down vote up
public Object unproxy(Object object) {
	Object result = object;
	
	if (object != null && isProxy(object)) {
		try{
		Hibernate.initialize(object);
		HibernateProxy proxy = (HibernateProxy) object;
		result = proxy
			.getHibernateLazyInitializer()
			.getImplementation();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	return result;
}
 
Example 40
Project: webdsl   File: ProxyHashSet.java   View source code 6 votes vote down vote up
/**
 * Removes the specified element from this set if it is present.
 * More formally, removes an element <tt>e</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>,
 * if this set contains such an element.  Returns <tt>true</tt> if
 * this set contained the element (or equivalently, if this set
 * changed as a result of the call).  (This set will not contain the
 * element once the call returns.)
 *
 * @param o object to be removed from this set, if present
 * @return <tt>true</tt> if the set contained the specified element
 */
public boolean remove(Object o) {
	if(o == null) { // Can't call getId on null, so always return false
		return false;
	}
	else if(o instanceof WebDSLEntity) {
		if(o instanceof HibernateProxy) {
			return map.remove((UUID)((HibernateProxy)o).getHibernateLazyInitializer().getIdentifier()) != null;
		}
		else {
			return map.remove(((WebDSLEntity)o).getId()) != null;
		}
	} else {
		return false;
	}
}