Example usage for org.hibernate.proxy HibernateProxy getHibernateLazyInitializer

List of usage examples for org.hibernate.proxy HibernateProxy getHibernateLazyInitializer

Introduction

In this page you can find the example usage for org.hibernate.proxy HibernateProxy getHibernateLazyInitializer.

Prototype

public LazyInitializer getHibernateLazyInitializer();

Source Link

Document

Get the underlying lazy initialization handler.

Usage

From source file:gr.interamerican.bo2.impl.open.hibernate.HibernateBo2Utils.java

License:Open Source License

/**
 * Checks if the persistence context contains an object.
 * //from w w w.j  a  va  2  s  .  c o m
 * This utility does not use a strictly public hibernate API.
 * 
 * @param object
 *        Object to check for.
 * @param s
 *        Session instance.
 *        
 * @return Returns true, if this object is contained in the persistence context.
 */
@SuppressWarnings("nls")
public static boolean sessionContains(Object object, Session s) {
    Serializable identifier = null;
    String entityName = null;

    if (object instanceof HibernateProxy) {
        HibernateProxy proxy = (HibernateProxy) object;
        identifier = proxy.getHibernateLazyInitializer().getIdentifier();
        entityName = proxy.getHibernateLazyInitializer().getEntityName();
    } else if (object instanceof PersistentObject) {
        PersistentObject<?> po = (PersistentObject<?>) object;
        identifier = po.getKey();
        entityName = Factory.declarationTypeName(object.getClass());
    }

    if (identifier == null) {
        return false;
    }

    SessionImplementor sessionImpl = (SessionImplementor) s;
    EntityPersister entityPersister = sessionImpl.getFactory().getEntityPersister(entityName);
    PersistenceContext persistenceContext = sessionImpl.getPersistenceContext();
    EntityKey entityKey = new EntityKey(identifier, entityPersister, EntityMode.POJO);
    Object entity = persistenceContext.getEntity(entityKey);

    boolean contains = entity != null;
    boolean differentInstances = object != entity;

    if (contains && differentInstances && logger.isDebugEnabled()) {
        logger.warn("Entity with identifier " + identifier
                + " was already associated with the Session as another instance.");
    }

    return contains;
}

From source file:gr.interamerican.bo2.impl.open.hibernate.TestProxySessionPropagation.java

License:Open Source License

/**
 * Demonstrates that an uninitialized Customer proxy will get
 * a Session instance when the Invoice is reattached and it will
 * be possible to initialize the CustomerAddress set. 
 * /*from   w  w w.j  av a  2  s  .  c om*/
 * @throws LogicException 
 * @throws DataException 
 * @throws UnexpectedException 
 */
@Test
public void testUninitializedProxiesReattachOK() throws UnexpectedException, DataException, LogicException {
    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            invoice = Factory.create(Invoice.class);
            invoice.setInvoiceNo(invoiceNo);
            PersistenceWorker<Invoice> ipw = openPw(Invoice.class);
            invoice = ipw.read(invoice);
        }
    }.execute();

    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            PoUtils.reattach(invoice, getProvider());

            Customer c = invoice.getCustomer().getCustomer();
            Assert.assertTrue(c instanceof HibernateProxy);
            HibernateProxy cProxy = (HibernateProxy) c;
            Assert.assertTrue(cProxy.getHibernateLazyInitializer().isUninitialized());
            Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession());
        }
    }.execute();

    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            PoUtils.reattach(invoice, getProvider());

            Customer c = invoice.getCustomer().getCustomer();
            Assert.assertTrue(c instanceof HibernateProxy);
            HibernateProxy cProxy = (HibernateProxy) c;
            Assert.assertTrue(cProxy.getHibernateLazyInitializer().isUninitialized());
            Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession());

            c.getAddresses().size();
        }
    }.execute();

}

From source file:gr.interamerican.bo2.impl.open.hibernate.TestProxySessionPropagation.java

License:Open Source License

/**
 * Demonstrates that an initialized Customer proxy will not get
 * a Session instance when the Invoice is reattached and it will
 * be impossible to initialize the CustomerAddress set. 
 * //www  . j  a  v  a  2s. c  o  m
 * @throws LogicException 
 * @throws DataException 
 * @throws UnexpectedException 
 */
@Test
public void testInitializedProxiesReattachOK() throws UnexpectedException, DataException, LogicException {
    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            invoice = Factory.create(Invoice.class);
            invoice.setInvoiceNo(invoiceNo);
            PersistenceWorker<Invoice> ipw = openPw(Invoice.class);
            invoice = ipw.read(invoice);
        }
    }.execute();

    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            PoUtils.reattach(invoice, getProvider());

            Customer c = invoice.getCustomer().getCustomer();
            Assert.assertTrue(c instanceof HibernateProxy);
            HibernateProxy cProxy = (HibernateProxy) c;
            Assert.assertTrue(cProxy.getHibernateLazyInitializer().isUninitialized());
            Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession());
            c.getCustomerName();
            Assert.assertFalse(cProxy.getHibernateLazyInitializer().isUninitialized());
        }
    }.execute();

    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            PoUtils.reattach(invoice, getProvider());

            Customer c = invoice.getCustomer().getCustomer();
            Assert.assertTrue(c instanceof HibernateProxy);
            HibernateProxy cProxy = (HibernateProxy) c;
            Assert.assertFalse(cProxy.getHibernateLazyInitializer().isUninitialized());
            Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession());

            c.getAddresses().size();
        }
    }.execute();

}

From source file:gr.interamerican.bo2.impl.open.hibernate.TestProxySessionPropagation.java

License:Open Source License

/**
 * Demonstrates that a many-to-one customer instance reattached with 
 * session.buildLockRequest(LockOptions.NONE).lock(customer) will not
 * have its modification record altered on the next session.flush, i.e.
 * no SQL associated with this entity will be sent to the database. 
 * //  w  w w.j  a v  a 2s  . c om
 * @throws UnexpectedException
 * @throws DataException
 * @throws LogicException
 */
@Test
public void testManyToOneNoCascadeReattachedAreNotFlushed()
        throws UnexpectedException, DataException, LogicException {
    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            invoice = Factory.create(Invoice.class);
            invoice.setInvoiceNo(invoiceNo);
            PersistenceWorker<Invoice> ipw = openPw(Invoice.class);
            invoice = ipw.read(invoice);
        }
    }.execute();

    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            PoUtils.reattach(invoice, getProvider());

            Customer c = invoice.getCustomer().getCustomer();
            Assert.assertTrue(c instanceof HibernateProxy);
            HibernateProxy cProxy = (HibernateProxy) c;
            Assert.assertTrue(cProxy.getHibernateLazyInitializer().isUninitialized());
            Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession());
            c.getCustomerName();
            Assert.assertFalse(cProxy.getHibernateLazyInitializer().isUninitialized());
        }
    }.execute();

    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            PoUtils.reattach(invoice, getProvider());

            Customer c = invoice.getCustomer().getCustomer();
            Assert.assertTrue(c instanceof HibernateProxy);
            HibernateProxy cProxy = (HibernateProxy) c;
            Assert.assertFalse(cProxy.getHibernateLazyInitializer().isUninitialized());
            Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession());

            customerLastModified = c.getLastModified();

            Session s = getProvider().getResource("LOCALDB", HibernateSessionProvider.class) //$NON-NLS-1$
                    .getHibernateSession();
            s.buildLockRequest(LockOptions.NONE).lock(c);

            Assert.assertEquals(customerLastModified, c.getLastModified());

            Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession());
            c.getAddresses().size();

            PersistenceWorker<Invoice> ipw = openPw(Invoice.class);
            ipw.store(invoice); //flush the session
        }
    }.execute();

    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            PersistenceWorker<Customer> cpw = openPw(Customer.class);
            Customer c = Factory.create(Customer.class);
            c.setCustomerNo(customerNo);
            c = cpw.read(c);
            Assert.assertEquals(customerLastModified, c.getLastModified());
        }
    }.execute();

}

From source file:gr.interamerican.bo2.impl.open.hibernate.TestProxySessionPropagation.java

License:Open Source License

/**
 * Demonstrates that a many-to-one customer instance reattached with 
 * session.buildLockRequest(LockOptions.NONE).lock(customer) will have
 * SQL sent on the next session.flush if it has been modified. 
 * //from www . j  a v a2 s  .  co  m
 * @throws UnexpectedException
 * @throws DataException
 * @throws LogicException
 */
@Test
public void testDirtyManyToOneNoCascadeReattachedFlush()
        throws UnexpectedException, DataException, LogicException {
    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            invoice = Factory.create(Invoice.class);
            invoice.setInvoiceNo(invoiceNo);
            PersistenceWorker<Invoice> ipw = openPw(Invoice.class);
            invoice = ipw.read(invoice);
        }
    }.execute();

    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            PoUtils.reattach(invoice, getProvider());

            Customer c = invoice.getCustomer().getCustomer();
            Assert.assertTrue(c instanceof HibernateProxy);
            HibernateProxy cProxy = (HibernateProxy) c;
            Assert.assertTrue(cProxy.getHibernateLazyInitializer().isUninitialized());
            Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession());
            c.getCustomerName();
            Assert.assertFalse(cProxy.getHibernateLazyInitializer().isUninitialized());
        }
    }.execute();

    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            PoUtils.reattach(invoice, getProvider());

            Customer c = invoice.getCustomer().getCustomer();
            Assert.assertTrue(c instanceof HibernateProxy);
            HibernateProxy cProxy = (HibernateProxy) c;
            Assert.assertFalse(cProxy.getHibernateLazyInitializer().isUninitialized());
            Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession());

            customerLastModified = c.getLastModified();

            Session s = getProvider().getResource("LOCALDB", HibernateSessionProvider.class) //$NON-NLS-1$
                    .getHibernateSession();
            s.buildLockRequest(LockOptions.NONE).lock(c);

            Assert.assertEquals(customerLastModified, c.getLastModified());

            Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession());
            c.getAddresses().size();
            c.setCustomerName(customerName); //make Customer dirty

            PersistenceWorker<Invoice> ipw = openPw(Invoice.class);
            ipw.store(invoice); //flush the session
        }
    }.execute();

    new AbstractBo2RuntimeCmd() {
        @Override
        public void work() throws LogicException, DataException, InitializationException, UnexpectedException {
            PersistenceWorker<Customer> cpw = openPw(Customer.class);
            Customer c = Factory.create(Customer.class);
            c.setCustomerNo(customerNo);
            c = cpw.read(c);
            Assert.assertEquals(customerName, c.getCustomerName());
        }
    }.execute();

}

From source file:gr.interamerican.bo2.impl.open.hibernate.utils.reflect.analyze.ModificationRecordFieldsAnalyzer.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected List<VariableDefinition<?>> whichFieldsToInclude(Object object) {
    List<VariableDefinition<?>> list = new ArrayList<VariableDefinition<?>>();
    if (object == null) {
        return list;
    }/*from   w w  w .  j a  v  a 2  s. co  m*/
    List<Field> fieldsToInclude = getFieldsToInclude(object.getClass());

    /*
     * Create VariableDefinitions for all fields produced before, taking special care of
     * field values that are either HibernateProxy or PersistentCollection instances.
     * [*] Uninitialized HibernateProxy and PersistentCollections do not have a VariableDefinition created.
     * [*] Initialized HibernateProxy objects are unwrapped if wrapped.
     * [*] Initialized PersistentCollections have a special VariableDefinition sub-type created for them.
     */
    for (Field field : fieldsToInclude) {
        field.setAccessible(true);
        Object value = ReflectionUtils.get(field, object);
        VariableDefinition vd = null;

        if (value instanceof HibernateProxy) {
            HibernateProxy proxy = (HibernateProxy) value;
            if (proxy.getHibernateLazyInitializer().isUninitialized()) {
                logger.debug("Ignoring uninitialized proxy of: " //$NON-NLS-1$
                        + proxy.getHibernateLazyInitializer().getEntityName());
                continue;
            }
            if (!proxy.getHibernateLazyInitializer().isUnwrap()) {
                logger.debug("Unwrapping initialized proxy of: " //$NON-NLS-1$
                        + proxy.getHibernateLazyInitializer().getEntityName());
                if (PersistentObject.class.isAssignableFrom(field.getType())) {
                    vd = new VariableDefinitionForPersistentObjects(field.getName(), field.getType());
                    vd.setValue(proxy.getHibernateLazyInitializer().getImplementation());
                } else {
                    vd = VariableDefinitionFactory.create(field);
                    vd.setValue(value);
                }
            }
        } else if (value instanceof PersistentCollection) {
            PersistentCollection coll = (PersistentCollection) value;
            if (!coll.wasInitialized()) {
                logger.debug("Ignoring uninitialized PersistentCollection of: " + coll.getRole()); //$NON-NLS-1$
                continue;
            }
            vd = new VariableDefinitionForPersistentCollections(field.getName(), field.getType());
            vd.setValue(value);
        } else if (value instanceof PersistentObject) {
            vd = new VariableDefinitionForPersistentObjects(field.getName(), field.getType());
            vd.setValue(value);
        } else {
            vd = VariableDefinitionFactory.create(field);
            vd.setValue(value);
        }
        list.add(vd);
    }
    return list;
}

From source file:gr.interamerican.bo2.impl.open.po.PoReattachAnalysis.java

License:Open Source License

public PoReattachAnalysisResult execute(AbstractBasePo<?> a) {
    PoReattachAnalysisResult analysis = new PoReattachAnalysisResult();

    analysis.getPosToReattachManually().addAll(getReferences(a));
    if (HibernateBo2Utils.isTransient(a)) {
        analysis.getTransientPos().add(a);
    }//  w  w  w  .j av a 2  s.  c om

    for (Object child : ReflectionUtils.get(a.getChildFields(), a)) {
        if (child instanceof HibernateProxy) {
            HibernateProxy proxy = (HibernateProxy) child;
            if (proxy.getHibernateLazyInitializer().isUninitialized()) {
                continue;
            }
            PoReattachAnalysisResult intermediate = INSTANCE
                    .execute((AbstractBasePo<?>) proxy.getHibernateLazyInitializer().getImplementation());
            analysis.getPosToReattachManually().addAll(intermediate.getPosToReattachManually());
            analysis.getTransientPos().addAll(intermediate.getTransientPos());
        } else if (child instanceof PersistentCollection) {
            PersistentCollection pColl = (PersistentCollection) child;
            if (!pColl.wasInitialized()) {
                continue;
            }
            for (Object obj : (Collection<?>) pColl) {
                if (obj instanceof HibernateProxy) {
                    HibernateProxy proxy = (HibernateProxy) obj;
                    if (proxy.getHibernateLazyInitializer().isUninitialized()) {
                        continue;
                    }
                    PoReattachAnalysisResult intermediate = INSTANCE.execute(
                            (AbstractBasePo<?>) proxy.getHibernateLazyInitializer().getImplementation());
                    analysis.getPosToReattachManually().addAll(intermediate.getPosToReattachManually());
                    analysis.getTransientPos().addAll(intermediate.getTransientPos());
                } else if (obj instanceof AbstractBasePo) {
                    PoReattachAnalysisResult intermediate = INSTANCE.execute((AbstractBasePo<?>) obj);
                    analysis.getPosToReattachManually().addAll(intermediate.getPosToReattachManually());
                    analysis.getTransientPos().addAll(intermediate.getTransientPos());
                }
            }
        } else if (child instanceof AbstractBasePo) {
            PoReattachAnalysisResult intermediate = INSTANCE.execute((AbstractBasePo<?>) child);
            analysis.getPosToReattachManually().addAll(intermediate.getPosToReattachManually());
            analysis.getTransientPos().addAll(intermediate.getTransientPos());
        } else if (child instanceof Collection) {
            for (Object obj : (Collection<?>) child) {
                if (obj instanceof AbstractBasePo) {
                    PoReattachAnalysisResult intermediate = INSTANCE.execute((AbstractBasePo<?>) obj);
                    analysis.getPosToReattachManually().addAll(intermediate.getPosToReattachManually());
                    analysis.getTransientPos().addAll(intermediate.getTransientPos());
                }
            }
        }
    }

    return analysis;
}

From source file:love.sola.netsupport.sql.TableTicket.java

License:Open Source License

/**
 * this is a hacky method to initialize all related entities of ticket
 *///from w w w  .  jav  a  2  s  .c om
public static List<Object[]> initializeTickets(List<Object[]> resultList) {
    for (Object[] result : resultList) {
        Ticket value = ((Ticket) result[0]);
        HibernateProxy proxiedUser = (HibernateProxy) value.getUser();
        if (proxiedUser != null) {
            User unproxiedUser = ((User) proxiedUser.getHibernateLazyInitializer().getImplementation());
            value.setUser(unproxiedUser);
        }
        HibernateProxy proxiedOperator = (HibernateProxy) value.getOperator();
        if (proxiedOperator != null) {
            Operator unproxiedOperator = ((Operator) proxiedOperator.getHibernateLazyInitializer()
                    .getImplementation());
            value.setOperator(unproxiedOperator);
        }
    }
    return resultList;
}

From source file:mojo.core.util.XHProxyConverter.java

License:Open Source License

@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
    logger.debug("### Hibernate proxy");

    if (Hibernate.isInitialized(source)) {
        logger.debug("### Unwrapping value");
        HibernateProxy proxy = (HibernateProxy) source;
        LazyInitializer initializer = proxy.getHibernateLazyInitializer();
        context.convertAnother(initializer.getImplementation());
    }/* w w w  .j ava 2s.co  m*/
}

From source file:net.digitalprimates.persistence.translators.hibernate.HibernateSerializer.java

License:Open Source License

private Object writeHibernateProxy(Object obj, Object key) {
    Object result;//from   ww  w  . jav a  2 s. co  m
    HibernateProxy hibProxy = (HibernateProxy) obj;

    ASObject as = new ASObject();
    as.setType(getClassName(obj));
    as.put(HibernateProxyConstants.UID, UUID.randomUUID().toString());
    as.put(HibernateProxyConstants.PKEY, hibProxy.getHibernateLazyInitializer().getIdentifier());
    as.put(HibernateProxyConstants.PROXYINITIALIZED, false);// !hibProxy.getHibernateLazyInitializer().isUninitialized());

    cache.put(key, as);
    result = as;
    return result;
}