List of usage examples for org.hibernate.proxy HibernateProxy getHibernateLazyInitializer
public LazyInitializer getHibernateLazyInitializer();
From source file:org.granite.hibernate.HibernateClassGetter.java
License:Open Source License
@Override public Class<?> getClass(Object o) { if (o instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) o; LazyInitializer initializer = proxy.getHibernateLazyInitializer(); String className = (initializer.isUninitialized() ? initializer.getEntityName() : initializer.getImplementation().getClass().getName()); if (className != null && className.length() > 0) { try { return TypeUtil.forName(className); } catch (Exception e) { log.warn(e, "Could not get class with initializer: %s for: %s", initializer.getClass().getName(), className); }// w w w . j av a 2s . com } // fallback... return initializer.getPersistentClass(); } return super.getClass(o); }
From source file:org.granite.hibernate.HibernateExternalizer.java
License:Open Source License
@Override public void writeExternal(Object o, ObjectOutput out) throws IOException, IllegalAccessException { ClassGetter classGetter = GraniteContext.getCurrentInstance().getGraniteConfig().getClassGetter(); Class<?> oClass = classGetter.getClass(o); String detachedState = null;/* w w w . ja v a 2 s . c o m*/ if (o instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) o; detachedState = getProxyDetachedState(proxy); // Only write initialized flag & detachedState & entity id if proxy is uninitialized. if (proxy.getHibernateLazyInitializer().isUninitialized()) { Serializable id = proxy.getHibernateLazyInitializer().getIdentifier(); log.debug("Writing uninitialized HibernateProxy %s with id %s", detachedState, id); // Write initialized flag. out.writeObject(Boolean.FALSE); // Write detachedState. out.writeObject(detachedState); // Write entity id. out.writeObject(id); return; } // Proxy is initialized, get the underlying persistent object. log.debug("Writing initialized HibernateProxy..."); o = proxy.getHibernateLazyInitializer().getImplementation(); } if (!isRegularEntity(o.getClass()) && !isEmbeddable(o.getClass())) { // @Embeddable or others... log.debug("Delegating non regular entity writing to DefaultExternalizer..."); super.writeExternal(o, out); } else { if (isRegularEntity(o.getClass())) { // Write initialized flag. out.writeObject(Boolean.TRUE); // Write detachedState. out.writeObject(detachedState); } // Externalize entity fields. List<Property> fields = findOrderedFields(oClass, false); log.debug("Writing entity %s with fields %s", o.getClass().getName(), fields); for (Property field : fields) { Object value = field.getProperty(o); // Persistent collections. if (value instanceof PersistentCollection) value = newExternalizableCollection((PersistentCollection) value); // Transient maps. else if (value instanceof Map<?, ?>) value = BasicMap.newInstance((Map<?, ?>) value); if (isValueIgnored(value)) out.writeObject(null); else out.writeObject(value); } } }
From source file:org.granite.hibernate.HibernateExternalizer.java
License:Open Source License
protected String getProxyDetachedState(HibernateProxy proxy) { LazyInitializer initializer = proxy.getHibernateLazyInitializer(); StringBuilder sb = new StringBuilder(); sb.append(initializer.getClass().getName()).append(':'); if (initializer.getPersistentClass() != null) sb.append(initializer.getPersistentClass().getName()); sb.append(':'); if (initializer.getEntityName() != null) sb.append(initializer.getEntityName()); return sb.toString(); }
From source file:org.granite.hibernate.jmf.EntityCodec.java
License:Open Source License
public void encode(ExtendedObjectOutput out, Object v) throws IOException, IllegalAccessException, InvocationTargetException { String detachedState = null;/* ww w .j a v a 2s.c o m*/ if (v instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) v; // Only write initialized flag, detachedState & id if v is an uninitialized proxy. if (proxy.getHibernateLazyInitializer().isUninitialized()) { Class<?> persistentClass = proxy.getHibernateLazyInitializer().getPersistentClass(); if (!serializableProxyAdapters.containsKey(persistentClass)) { try { SerializableProxyAdapter proxyAdapter = new SerializableProxyAdapter(proxy.writeReplace()); serializableProxyAdapters.putIfAbsent(persistentClass, proxyAdapter); } catch (Exception e) { throw new IOException("Could not create SerializableProxyAdapter for: " + proxy); } } Serializable id = proxy.getHibernateLazyInitializer().getIdentifier(); log.debug("Writing uninitialized HibernateProxy %s with id %s", detachedState, id); out.writeBoolean(false); out.writeUTF(null); out.writeObject(id); return; } // Proxy is initialized, get the underlying persistent object. log.debug("Writing initialized HibernateProxy..."); v = proxy.getHibernateLazyInitializer().getImplementation(); } // Write initialized flag & detachedState. out.writeBoolean(true); out.writeUTF(null); // Write all fields in lexical order. List<Property> fields = out.getReflection().findSerializableFields(v.getClass()); for (Property field : fields) out.getAndWriteField(v, field); }
From source file:org.granite.hibernate4.HibernateExternalizer.java
License:Open Source License
@Override public void writeExternal(Object o, ObjectOutput out) throws IOException, IllegalAccessException { ClassGetter classGetter = GraniteContext.getCurrentInstance().getGraniteConfig().getClassGetter(); Class<?> oClass = classGetter.getClass(o); String detachedState = null;//from ww w. j a v a 2s . c om if (o instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) o; detachedState = getProxyDetachedState(proxy); // Only write initialized flag & detachedState & entity id if proxy is uninitialized. if (proxy.getHibernateLazyInitializer().isUninitialized()) { Serializable id = proxy.getHibernateLazyInitializer().getIdentifier(); log.debug("Writing uninitialized HibernateProxy %s with id %s", detachedState, id); // Write initialized flag. out.writeObject(Boolean.FALSE); // Write detachedState. out.writeObject(detachedState); // Write entity id. out.writeObject(id); return; } // Proxy is initialized, get the underlying persistent object. log.debug("Writing initialized HibernateProxy..."); o = proxy.getHibernateLazyInitializer().getImplementation(); } if (!isRegularEntity(o.getClass()) && !isEmbeddable(o.getClass())) { // @Embeddable or others... log.debug("Delegating non regular entity writing to DefaultExternalizer..."); super.writeExternal(o, out); } else { if (isRegularEntity(o.getClass())) { // Write initialized flag. out.writeObject(Boolean.TRUE); // Write detachedState. out.writeObject(null); } // Externalize entity fields. List<Property> fields = findOrderedFields(oClass, false); log.debug("Writing entity %s with fields %s", o.getClass().getName(), fields); for (Property field : fields) { Object value = field.getProperty(o); // Persistent collections. if (value instanceof PersistentCollection) value = newExternalizableCollection((PersistentCollection) value); // Transient maps. else if (value instanceof Map<?, ?>) value = BasicMap.newInstance((Map<?, ?>) value); if (isValueIgnored(value)) out.writeObject(null); else out.writeObject(value); } } }
From source file:org.granite.hibernate4.jmf.EntityCodec.java
License:Open Source License
public void encode(ExtendedObjectOutput out, Object v) throws IOException, IllegalAccessException, InvocationTargetException { if (v instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) v; // Only write initialized flag, detachedState & id if v is an uninitialized proxy. if (proxy.getHibernateLazyInitializer().isUninitialized()) { Class<?> persistentClass = proxy.getHibernateLazyInitializer().getPersistentClass(); if (!serializableProxyAdapters.containsKey(persistentClass)) { try { SerializableProxyAdapter proxyAdapter = new SerializableProxyAdapter(proxy); serializableProxyAdapters.putIfAbsent(persistentClass, proxyAdapter); } catch (Exception e) { throw new IOException("Could not create SerializableProxyAdapter for: " + proxy); }/*w w w.j a va 2 s.co m*/ } Serializable id = proxy.getHibernateLazyInitializer().getIdentifier(); log.debug("Writing uninitialized HibernateProxy %s with id %s", persistentClass, id); out.writeBoolean(false); out.writeUTF(null); out.writeObject(id); return; } // Proxy is initialized, get the underlying persistent object. log.debug("Writing initialized HibernateProxy..."); v = proxy.getHibernateLazyInitializer().getImplementation(); } // Write initialized flag & detachedState. out.writeBoolean(true); out.writeUTF(null); // Write all properties in lexical order. List<Property> properties = out.getReflection().findSerializableProperties(v.getClass()); for (Property property : properties) out.getAndWriteProperty(v, property); }
From source file:org.hoteia.qalingo.core.domain.AbstractEntity.java
License:Apache License
public <E> E deproxy(E obj) { if (obj == null) return obj; if (obj instanceof HibernateProxy) { // Unwrap Proxy; // -- loading, if necessary. HibernateProxy proxy = (HibernateProxy) obj; LazyInitializer li = proxy.getHibernateLazyInitializer(); return (E) li.getImplementation(); }/*from ww w. j a va 2 s .c o m*/ return obj; }
From source file:org.jspresso.framework.application.backend.persistence.hibernate.ControllerAwareEntityProxyInterceptor.java
License:Open Source License
/** * {@inheritDoc}/*from w w w . j av a 2s.co m*/ */ @SuppressWarnings("unchecked") @Override public Object 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); } // getEntity should never return transient instances, see #1244 if (registeredEntity != null && !registeredEntity.isPersistent()) { registeredEntity = null; } ((HibernateBackendController) getBackendController()).detachFromHibernateInDepth(registeredEntity, ((HibernateBackendController) getBackendController()).getHibernateSession(), new HibernateEntityRegistry("detachFromHibernateInDepth")); return registeredEntity; }
From source file:org.jspresso.framework.application.backend.persistence.hibernate.HibernateBackendController.java
License:Open Source License
/** * {@inheritDoc}/*from ww w .ja v a 2 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 av a 2 s .c o m*/ } 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); } }