Example usage for org.hibernate.proxy LazyInitializer getSession

List of usage examples for org.hibernate.proxy LazyInitializer getSession

Introduction

In this page you can find the example usage for org.hibernate.proxy LazyInitializer getSession.

Prototype

SharedSessionContractImplementor getSession();

Source Link

Document

Get the session to which this proxy is associated, or null if it is not attached.

Usage

From source file:ch.algotrader.dao.HibernateInitializer.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T extends BaseEntityI> T initializeProxy(BaseEntityI entity, String context, T proxy) {

    if (proxy instanceof HibernateProxy) {

        HibernateProxy hibernateProxy = (HibernateProxy) proxy;
        LazyInitializer initializer = hibernateProxy.getHibernateLazyInitializer();

        if (initializer.getSession() != null) {

            long before = System.nanoTime();
            proxy = (T) initializer.getImplementation();
            MetricsUtil.account(ClassUtils.getShortClassName(entity.getClass()) + context, (before));
        } else {//  w w  w.jav a  2s .  c o m
            throw new IllegalStateException("no hibernate session available");
        }
    }

    return proxy;
}

From source file:ch.systemsx.cisd.openbis.generic.shared.util.HibernateUtils.java

License:Apache License

/**
 * @return Unproxied <var>proxy</var>.
 *///from ww  w  . j av  a 2  s  .co  m
@SuppressWarnings({ "unchecked" })
public final static <T> T unproxy(final T proxy) {
    if (proxy instanceof HibernateProxy && Hibernate.isInitialized(proxy)) {
        LazyInitializer lazyInitializer = ((HibernateProxy) proxy).getHibernateLazyInitializer();
        SessionImplementor sessionImplementor = lazyInitializer.getSession();
        // check if the given bean still has a session instance attached
        if (sessionImplementor != null) {
            // use the unproxy method of the persistenceContext class
            return (T) sessionImplementor.getPersistenceContext().unproxy(proxy);
        } else {
            // return the wrapped bean instance if there's no active session instance available
            return (T) lazyInitializer.getImplementation();
        }
    } else {
        // not a proxy - nothing to do
        return proxy;
    }
}

From source file:org.beangle.commons.orm.hibernate.HibernateEntityDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public <T> T initialize(T proxy) {
    if (proxy instanceof HibernateProxy) {
        LazyInitializer init = ((HibernateProxy) proxy).getHibernateLazyInitializer();
        if (null == init.getSession() || init.getSession().isClosed()) {
            proxy = (T) getSession().get(init.getEntityName(), init.getIdentifier());
        } else {//from  w ww  .ja  v a2s  . com
            Hibernate.initialize(proxy);
        }
    } else if (proxy instanceof PersistentCollection) {
        Hibernate.initialize(proxy);
    }
    return proxy;
}

From source file:org.beangle.model.persist.hibernate.HibernateEntityDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public <T> T initialize(T proxy) {
    if (proxy instanceof HibernateProxy) {
        LazyInitializer init = ((HibernateProxy) proxy).getHibernateLazyInitializer();
        if (null == init.getSession() || init.getSession().isClosed()) {
            proxy = (T) getHibernateTemplate().get(init.getEntityName(), init.getIdentifier());
        } else {/*from  w  ww .  j a  v  a2s. com*/
            getHibernateTemplate().initialize(proxy);
        }
    }
    return proxy;
}

From source file:org.directwebremoting.hibernate.H3BeanConverter.java

License:Apache License

/**
 * 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//from  w ww.j a  v  a2s  . co m
 */
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();
    }
}

From source file:org.directwebremoting.hibernate.H3PropertyDescriptorProperty.java

License:Apache License

@Override
public Object getValue(Object bean) throws ConversionException {
    if (!(bean instanceof HibernateProxy)) {
        // This is not a hibernate dynamic proxy, just use it
        return super.getValue(bean);
    } else {/*  w  w w  .  j a v  a 2  s. co m*/
        // If the property is already initialized, use it
        boolean initialized = Hibernate.isPropertyInitialized(bean, descriptor.getName());
        if (initialized) {
            // This might be a lazy-collection so we need to double check
            Object reply = super.getValue(bean);
            initialized = Hibernate.isInitialized(reply);
        }

        if (initialized) {
            return super.getValue(bean);
        } else {
            // If the session bound to the property is live, use it
            HibernateProxy proxy = (HibernateProxy) bean;
            LazyInitializer initializer = proxy.getHibernateLazyInitializer();
            SessionImplementor implementor = initializer.getSession();
            if (implementor.isOpen()) {
                return super.getValue(bean);
            }

            // So the property needs database access, and the session is closed
            // We'll need to try get another session
            ServletContext context = WebContextFactory.get().getServletContext();
            Session session = H3SessionAjaxFilter.getCurrentSession(context);

            if (session != null) {
                session.update(bean);
                return super.getValue(bean);
            }

            return null;
        }
    }
}

From source file:org.directwebremoting.hibernate.H4PropertyDescriptorProperty.java

License:Apache License

@Override
public Object getValue(Object bean) throws ConversionException {
    if (!(bean instanceof HibernateProxy)) {
        // This is not a hibernate dynamic proxy, just use it
        return super.getValue(bean);
    } else {//  w ww. j  a v a 2 s .c  om
        // If the property is already initialized, use it
        boolean initialized = Hibernate.isPropertyInitialized(bean, descriptor.getName());
        if (initialized) {
            // This might be a lazy-collection so we need to double check
            Object reply = super.getValue(bean);
            initialized = Hibernate.isInitialized(reply);
        }

        if (initialized) {
            return super.getValue(bean);
        } else {
            // If the session bound to the property is live, use it
            HibernateProxy proxy = (HibernateProxy) bean;
            LazyInitializer initializer = proxy.getHibernateLazyInitializer();
            SessionImplementor implementor = initializer.getSession();
            if (implementor.isOpen()) {
                return super.getValue(bean);
            }

            // So the property needs database access, and the session is closed
            // We'll need to try get another session
            ServletContext context = WebContextFactory.get().getServletContext();
            Session session = H4SessionAjaxFilter.getCurrentSession(context);

            if (session != null) {
                session.update(bean);
                return super.getValue(bean);
            }

            return null;
        }
    }
}

From source file:org.jspresso.framework.application.backend.persistence.hibernate.HibernateBackendController.java

License:Open Source License

/**
 * {@inheritDoc}//from  w  ww . ja  va2  s.c  o m
 */
@Override
@SuppressWarnings("unchecked")
public void initializePropertyIfNeeded(final IComponent componentOrEntity, final String propertyName) {
    Object propertyValue = componentOrEntity.straightGetProperty(propertyName);
    if (!isInitialized(propertyValue)) {
        // turn off dirt tracking.
        boolean dirtRecorderWasEnabled = isDirtyTrackingEnabled();
        try {
            setDirtyTrackingEnabled(false);

            boolean isSessionEntity = isSessionEntity(componentOrEntity);
            boolean isUnitOfWorkActive = isUnitOfWorkActive();

            // Never initialize session entities from UOW session
            if (!(isUnitOfWorkActive && isSessionEntity)) {
                if (propertyValue instanceof Collection<?>
                        && propertyValue instanceof AbstractPersistentCollection) {
                    if (((AbstractPersistentCollection) propertyValue).getSession() != null
                            && ((AbstractPersistentCollection) propertyValue).getSession().isOpen()) {
                        try {
                            Hibernate.initialize(propertyValue);
                            relinkAfterInitialization((Collection<?>) propertyValue, componentOrEntity);
                        } catch (Exception ex) {
                            LOG.error("An internal error occurred when forcing {} collection initialization.",
                                    propertyName);
                            LOG.error("Source exception", ex);
                        }
                    }
                } else if (propertyValue instanceof HibernateProxy) {
                    HibernateProxy proxy = (HibernateProxy) propertyValue;
                    LazyInitializer li = proxy.getHibernateLazyInitializer();
                    if (li.getSession() != null && li.getSession().isOpen()) {
                        try {
                            Hibernate.initialize(propertyValue);
                        } catch (Exception ex) {
                            LOG.error("An internal error occurred when forcing {} reference initialization.",
                                    propertyName);
                            LOG.error("Source exception", ex);
                        }
                    }
                }
            }

            if (!isInitialized(propertyValue)) {
                if (currentInitializationSession != null) {
                    performPropertyInitializationUsingSession(componentOrEntity, propertyName,
                            currentInitializationSession);
                } else {
                    boolean suspendUnitOfWork = false;
                    boolean startUnitOfWork = false;
                    if (isSessionEntity) {
                        // Always use NoTxSession to initialize session entities
                        if (isUnitOfWorkActive) {
                            suspendUnitOfWork = true;
                        }
                    } else {
                        if (!isUnitOfWorkActive) {
                            // Never use NoTxSession to initialize non session entities (see bug #1153)
                            startUnitOfWork = true;
                        }
                    }
                    try {
                        if (suspendUnitOfWork) {
                            suspendUnitOfWork();
                        }
                        if (startUnitOfWork) {
                            getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
                                @Override
                                protected void doInTransactionWithoutResult(TransactionStatus status) {
                                    initializeProperty(componentOrEntity, propertyName);
                                    status.setRollbackOnly();
                                }
                            });
                        } else {
                            initializeProperty(componentOrEntity, propertyName);
                        }
                    } finally {
                        if (suspendUnitOfWork) {
                            resumeUnitOfWork();
                        }
                    }
                }
            }
            componentOrEntity.firePropertyChange(propertyName, IPropertyChangeCapable.UNKNOWN, propertyValue);
        } finally {
            setDirtyTrackingEnabled(dirtRecorderWasEnabled);
        }
    }
}

From source file:org.jspresso.framework.application.backend.persistence.hibernate.HibernateBackendController.java

License:Open Source License

@SuppressWarnings("unchecked")
private void performPropertyInitializationUsingSession(final IComponent componentOrEntity,
        final String propertyName, Session hibernateSession) {
    Object propertyValue = componentOrEntity.straightGetProperty(propertyName);
    if (!isInitialized(propertyValue)) {
        IEntityRegistry alreadyDetached = createEntityRegistry("detachFromHibernateInDepth");
        if (componentOrEntity instanceof IEntity) {
            if (((IEntity) componentOrEntity).isPersistent()) {
                detachFromHibernateInDepth(componentOrEntity, hibernateSession, alreadyDetached);
                lockInHibernate((IEntity) componentOrEntity, hibernateSession);
            } else if (IEntity.DELETED_VERSION.equals(((IEntity) componentOrEntity).getVersion())) {
                LOG.error("Trying to initialize a property ({}) on a deleted object ({} : {}).", propertyName,
                        componentOrEntity.getComponentContract().getName(), componentOrEntity);
                throw new RuntimeException("Trying to initialize a property (" + propertyName
                        + ") on a deleted object (" + componentOrEntity.getComponentContract().getName() + " : "
                        + componentOrEntity + ")");
            } else if (propertyValue instanceof IEntity) {
                detachFromHibernateInDepth((IEntity) propertyValue, hibernateSession, alreadyDetached);
                lockInHibernate((IEntity) propertyValue, hibernateSession);
            }/* ww w .  j a  va  2s  . c  om*/
        } else if (propertyValue instanceof IEntity) {
            // to handle initialization of component properties.
            detachFromHibernateInDepth((IEntity) propertyValue, hibernateSession, alreadyDetached);
            lockInHibernate((IEntity) propertyValue, hibernateSession);
        }

        if (propertyValue instanceof HibernateProxy) {
            HibernateProxy proxy = (HibernateProxy) propertyValue;
            LazyInitializer li = proxy.getHibernateLazyInitializer();
            if (li.getSession() == null) {
                try {
                    li.setSession((SessionImplementor) hibernateSession);
                } catch (Exception ex) {
                    LOG.error(
                            "An internal error occurred when re-associating Hibernate session for {} reference initialization.",
                            propertyName);
                    LOG.error("Source exception", ex);
                }
            }
        } else if (propertyValue instanceof AbstractPersistentCollection) {
            AbstractPersistentCollection apc = (AbstractPersistentCollection) propertyValue;
            if (apc.getSession() == null) {
                try {
                    apc.setCurrentSession((SessionImplementor) hibernateSession);
                } catch (Exception ex) {
                    LOG.error(
                            "An internal error occurred when re-associating Hibernate session for {} reference initialization.",
                            propertyName);
                    LOG.error("Source exception", ex);
                }
            }
        }
        Hibernate.initialize(propertyValue);
        if (propertyValue instanceof Collection<?> && propertyValue instanceof PersistentCollection) {
            relinkAfterInitialization((Collection<?>) propertyValue, componentOrEntity);
            for (Iterator<?> ite = ((Collection<?>) propertyValue).iterator(); ite.hasNext();) {
                Object collectionElement = ite.next();
                if (collectionElement instanceof IEntity) {
                    if (isEntityRegisteredForDeletion((IEntity) collectionElement)) {
                        ite.remove();
                    }
                }
            }
        } else {
            relinkAfterInitialization(Collections.singleton(propertyValue), componentOrEntity);
        }
        clearPropertyDirtyState(propertyValue);
    }
}

From source file:org.jspresso.framework.application.backend.persistence.hibernate.HibernateHelper.java

License:Open Source License

/**
 * Unset proxy hibernate session.//  www .ja v a2s.  c  o  m
 *
 * @param entity the entity
 * @param hibernateSession the hibernate session
 */
public static void unsetProxyHibernateSession(IEntity entity, Session hibernateSession) {
    if (entity instanceof HibernateProxy) {
        LazyInitializer li = ((HibernateProxy) entity).getHibernateLazyInitializer();
        if (li.getSession() != null && li.getSession() != hibernateSession) {
            li.unsetSession();
        }
    }
}