org.hibernate.proxy.HibernateProxy Java Examples

The following examples show how to use org.hibernate.proxy.HibernateProxy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: cacheonix-core   Author: cacheonix   File: Dom4jEntityTuplizer.java    License: GNU Lesser General Public License v2.1 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 #2
Source Project: cacheonix-core   Author: cacheonix   File: EntityType.java    License: GNU Lesser General Public License v2.1 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 #3
Source Project: cacheonix-core   Author: cacheonix   File: Hibernate.java    License: GNU Lesser General Public License v2.1 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 #4
Source Project: onedev   Author: theonedev   File: HibernateProxySerializer.java    License: MIT License 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 #5
Source Project: cacheonix-core   Author: cacheonix   File: EntityType.java    License: GNU Lesser General Public License v2.1 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 #6
Source Project: cacheonix-core   Author: cacheonix   File: SessionImpl.java    License: GNU Lesser General Public License v2.1 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 #7
Source Project: projectforge-webapp   Author: micromata   File: HibernateMapper.java    License: GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public String serializedClass(Class clazz)
{
  // check whether we are hibernate proxy and substitute real name
  for (int i = 0; i < clazz.getInterfaces().length; i++) {
    if (HibernateProxy.class.equals(clazz.getInterfaces()[i])) {
      // System.err.println("resolving to class name:" + clazz.getSuperclass().getName());
      return clazz.getSuperclass().getName();
    }
  }
  if (collectionMap.containsKey(clazz)) {
    // System.err.println("** substituting " + clazz + " with " + collectionMap.get(clazz));
    return ((Class) collectionMap.get(clazz)).getName();
  }

  return super.serializedClass(clazz);
}
 
Example #8
Source Project: cacheonix-core   Author: cacheonix   File: StatefulPersistenceContext.java    License: GNU Lesser General Public License v2.1 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 #9
Source Project: cacheonix-core   Author: cacheonix   File: StatefulPersistenceContext.java    License: GNU Lesser General Public License v2.1 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
Source Project: gorm-hibernate5   Author: grails   File: GrailsHibernateUtil.java    License: Apache License 2.0 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.setHibernateFlushMode(FlushMode.AUTO);
    incrementVersion(target);
}
 
Example #11
Source Project: we-cmdb   Author: WeBankPartners   File: JpaQueryUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> T findEager(EntityManager em, Class<T> type, Object id) {
    T entity = em.find(type, id);
    if (entity instanceof HibernateProxy) {
        entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer().getImplementation();
    }
    return entity;
}
 
Example #12
/**
 * Handle the given update event.
 *
 * @param event The update event to be handled.
 */
public void onSaveOrUpdate(SaveOrUpdateEvent event) {
	final SessionImplementor source = event.getSession();
	final Object object = event.getObject();
	final Serializable requestedId = event.getRequestedId();

	if ( requestedId != null ) {
		//assign the requested id to the proxy, *before* 
		//reassociating the proxy
		if ( object instanceof HibernateProxy ) {
			( ( HibernateProxy ) object ).getHibernateLazyInitializer().setIdentifier( requestedId );
		}
	}

	if ( reassociateIfUninitializedProxy( object, source ) ) {
		log.trace( "reassociated uninitialized proxy" );
		// an uninitialized proxy, noop, don't even need to 
		// return an id, since it is never a save()
	}
	else {
		//initialize properties of the event:
		final Object entity = source.getPersistenceContext().unproxyAndReassociate( object );
		event.setEntity( entity );
		event.setEntry( source.getPersistenceContext().getEntry( entity ) );
		//return the id in the event object
		event.setResultId( performSaveOrUpdate( event ) );
	}

}
 
Example #13
Source Project: wecube-platform   Author: WeBankPartners   File: JpaQueryUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> T findEager(EntityManager em, Class<T> type, Object id) {
    T entity = em.find(type, id);
    if (entity instanceof HibernateProxy) {
        entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer().getImplementation();
    }
    return entity;
}
 
Example #14
Source Project: uyuni   Author: uyuni-project   File: SaltServerActionService.java    License: GNU General Public License v2.0 5 votes vote down vote up
private Action unproxy(Action entity) {
    Hibernate.initialize(entity);
    if (entity instanceof HibernateProxy) {
        entity = (Action) ((HibernateProxy) entity).getHibernateLazyInitializer()
                .getImplementation();
    }
    return entity;
}
 
Example #15
Source Project: gorm-hibernate5   Author: grails   File: SimpleHibernateProxyHandler.java    License: Apache License 2.0 5 votes vote down vote up
public Class<?> getProxiedClass(Object o) {
    if(o instanceof HibernateProxy) {
        return HibernateProxyHelper.getClassWithoutInitializingProxy(o);
    }
    else {
        return super.getProxiedClass(o);
    }
}
 
Example #16
Source Project: onedev   Author: theonedev   File: HibernateProxySerializer.java    License: MIT License 5 votes vote down vote up
@Override
public void serialize(HibernateProxy value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {
	Object proxiedValue = findProxied(value);
	// TODO: figure out how to suppress nulls, if necessary? (too late for
	// that here)
	if (proxiedValue == null) {
		provider.defaultSerializeNull(jgen);
		return;
	}
	findSerializer(provider, proxiedValue).serialize(proxiedValue, jgen,
			provider);
}
 
Example #17
Source Project: sakai   Author: sakaiproject   File: HibernateUtils.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * THIS CAN BE REMOVED WHEN SAKAI IS ON HIBERNATE >= 5.2.10
 *
 * Unproxies a {@link HibernateProxy}. If the proxy is uninitialized, it automatically triggers an initialization.
 * In case the supplied object is null or not a proxy, the object will be returned as-is.
 *
 * @param proxy the {@link HibernateProxy} to be unproxied
 * @return the proxy's underlying implementation object, or the supplied object otherwise
 */
public static Object unproxy(Object proxy) {
    if ( proxy instanceof HibernateProxy ) {
        HibernateProxy hibernateProxy = (HibernateProxy) proxy;
        LazyInitializer initializer = hibernateProxy.getHibernateLazyInitializer();
        return initializer.getImplementation();
    } else {
        return proxy;
    }
}
 
Example #18
Source Project: cacheonix-core   Author: cacheonix   File: CascadingAction.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void noCascade(
		EventSource session,
		Object child,
		Object parent,
		EntityPersister persister,
		int propertyIndex) {
	if ( child == null ) {
		return;
	}
	Type type = persister.getPropertyTypes()[propertyIndex];
	if ( type.isEntityType() ) {
		String childEntityName = ( ( EntityType ) type ).getAssociatedEntityName( session.getFactory() );

		if ( ! isInManagedState( child, session )
				&& ! ( child instanceof HibernateProxy ) //a proxy cannot be transient and it breaks ForeignKeys.isTransient
				&& ForeignKeys.isTransient( childEntityName, child, null, session ) ) {
			String parentEntiytName = persister.getEntityName();
			String propertyName = persister.getPropertyNames()[propertyIndex];
			throw new TransientObjectException(
					"object references an unsaved transient instance - " +
					"save the transient instance before flushing: " +
					parentEntiytName + "." + propertyName + " -> " + childEntityName
			);

		}
	}
}
 
Example #19
Source Project: rapidoid   Author: rapidoid   File: JPAUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> T _unproxy(T entity) {
	if (Cls.exists("org.hibernate.proxy.HibernateProxy") && entity instanceof HibernateProxy) {
		entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer().getImplementation();
	}

	return entity;
}
 
Example #20
Source Project: lams   Author: lamsfoundation   File: AbstractEntityTuplizer.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Serializable determineEntityId(
		Object entity,
		AssociationType associationType,
		SharedSessionContractImplementor session,
		SessionFactoryImplementor sessionFactory) {
	if ( entity == null ) {
		return null;
	}

	if ( HibernateProxy.class.isInstance( entity ) ) {
		// entity is a proxy, so we know it is not transient; just return ID from proxy
		return ( (HibernateProxy) entity ).getHibernateLazyInitializer().getIdentifier();
	}

	if ( session != null ) {
		final EntityEntry pcEntry = session.getPersistenceContext().getEntry( entity );
		if ( pcEntry != null ) {
			// entity managed; return ID.
			return pcEntry.getId();
		}
	}

	final EntityPersister persister = resolveEntityPersister(
			entity,
			associationType,
			session,
			sessionFactory
	);

	return persister.getIdentifier( entity, session );
}
 
Example #21
Source Project: lams   Author: lamsfoundation   File: PersistenceUnitUtilImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object getIdentifier(Object entity) {
	if ( entity == null ) {
		throw new IllegalArgumentException( "Passed entity cannot be null" );
	}

	if ( entity instanceof HibernateProxy ) {
		return ((HibernateProxy) entity).getHibernateLazyInitializer().getIdentifier();
	}
	else if ( entity instanceof ManagedEntity ) {
		EntityEntry entityEntry = ((ManagedEntity) entity).$$_hibernate_getEntityEntry();
		if ( entityEntry != null ) {
			return entityEntry.getId();
		}
		else {
			// HHH-11426 - best effort to deal with the case of detached entities
			log.debug( "javax.persistence.PersistenceUnitUtil.getIdentifier may not be able to read identifier of a detached entity" );
			return getIdentifierFromPersister( entity );
		}
	}
	else {
		log.debugf(
				"javax.persistence.PersistenceUnitUtil.getIdentifier is only intended to work with enhanced entities " +
						"(although Hibernate also adapts this support to its proxies); " +
						"however the passed entity was not enhanced (nor a proxy).. may not be able to read identifier"
		);
		return getIdentifierFromPersister( entity );
	}
}
 
Example #22
Source Project: gorm-hibernate5   Author: grails   File: SimpleHibernateProxyHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void initialize(Object o) {
    if (o instanceof HibernateProxy) {
        final LazyInitializer hibernateLazyInitializer = ((HibernateProxy)o).getHibernateLazyInitializer();
        if (hibernateLazyInitializer.isUninitialized()) {
            hibernateLazyInitializer.initialize();
        }
    }
    else {
        super.initialize(o);
    }
}
 
Example #23
Source Project: cacheonix-core   Author: cacheonix   File: JavassistProxyFactory.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public HibernateProxy getProxy(
		Serializable id,
        SessionImplementor session) throws HibernateException {
	return JavassistLazyInitializer.getProxy(
			factory,
	        entityName,
			persistentClass,
	        interfaces,
	        getIdentifierMethod,
			setIdentifierMethod,
	        componentIdType,
	        id,
	        session
	);
}
 
Example #24
Source Project: javers   Author: javers   File: HibernateUnproxyObjectAccessHook.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<ObjectAccessProxy<T>> createAccessor(T entity) {
    if (entity instanceof HibernateProxy) {
        LazyInitializer lazyInitializer = ((HibernateProxy) entity).getHibernateLazyInitializer();

        return fromLazyInitializer(lazyInitializer);
    }
    if (entity instanceof JavassistLazyInitializer){
        JavassistLazyInitializer proxy = (JavassistLazyInitializer) entity;
        return fromLazyInitializer(proxy);
    }

    return Optional.empty();
}
 
Example #25
Source Project: lams   Author: lamsfoundation   File: StatefulPersistenceContext.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void reassociateProxy(Object value, Serializable id) throws MappingException {
	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 #26
Source Project: lams   Author: lamsfoundation   File: StatefulPersistenceContext.java    License: GNU General Public License v2.0 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().getMetamodel().entityPersister( li.getEntityName() );
		final EntityKey key = session.generateEntityKey( li.getIdentifier(), persister );
	  	// any earlier proxy takes precedence
		proxiesByKey.putIfAbsent( key, proxy );
		proxy.getHibernateLazyInitializer().setSession( session );
	}
}
 
Example #27
Source Project: cacheonix-core   Author: cacheonix   File: EntityType.java    License: GNU Lesser General Public License v2.1 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 #28
Source Project: lams   Author: lamsfoundation   File: StatefulPersistenceContext.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setReadOnly(Object object, boolean readOnly) {
	if ( object == null ) {
		throw new AssertionFailure( "object must be non-null." );
	}
	if ( isReadOnly( object ) == readOnly ) {
		return;
	}
	if ( object instanceof HibernateProxy ) {
		final HibernateProxy proxy = (HibernateProxy) object;
		setProxyReadOnly( proxy, readOnly );
		if ( Hibernate.isInitialized( proxy ) ) {
			setEntityReadOnly(
					proxy.getHibernateLazyInitializer().getImplementation(),
					readOnly
			);
		}
	}
	else {
		setEntityReadOnly( object, readOnly );
		// PersistenceContext.proxyFor( entity ) returns entity if there is no proxy for that entity
		// so need to check the return value to be sure it is really a proxy
		final Object maybeProxy = getSession().getPersistenceContext().proxyFor( object );
		if ( maybeProxy instanceof HibernateProxy ) {
			setProxyReadOnly( (HibernateProxy) maybeProxy, readOnly );
		}
	}
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: StatefulPersistenceContext.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void setProxyReadOnly(HibernateProxy proxy, boolean readOnly) {
	if ( proxy.getHibernateLazyInitializer().getSession() != getSession() ) {
		throw new AssertionFailure(
				"Attempt to set a proxy to read-only that is associated with a different session" );
	}
	proxy.getHibernateLazyInitializer().setReadOnly( readOnly );
}
 
Example #30
Source Project: lams   Author: lamsfoundation   File: JavassistProxyFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public HibernateProxy getProxy(
		Serializable id,
		SharedSessionContractImplementor session) throws HibernateException {
	final JavassistLazyInitializer initializer = new JavassistLazyInitializer(
			entityName,
			persistentClass,
			interfaces,
			id,
			getIdentifierMethod,
			setIdentifierMethod,
			componentIdType,
			session,
			overridesEquals
	);

	try {
		final HibernateProxy proxy = (HibernateProxy) proxyClass.newInstance();
		( (Proxy) proxy ).setHandler( initializer );
		initializer.constructed();

		return proxy;
	}
	catch (Throwable t) {
		LOG.error( LOG.bytecodeEnhancementFailed( entityName ), t );
		throw new HibernateException( LOG.bytecodeEnhancementFailed( entityName ), t );
	}
}