Example usage for org.hibernate.engine.spi EntityEntry getStatus

List of usage examples for org.hibernate.engine.spi EntityEntry getStatus

Introduction

In this page you can find the example usage for org.hibernate.engine.spi EntityEntry getStatus.

Prototype

Status getStatus();

Source Link

Usage

From source file:org.babyfish.hibernate.collection.spi.persistence.AbstractBasePersistence.java

License:Open Source License

protected static <E> Collection<E> getOrphans(XCollection<E> oldElements, XCollection<E> currentElements,
        String entityName, SessionImplementor session) throws HibernateException {

    // short-circuit(s)
    if (currentElements.isEmpty()) {
        return oldElements; // no new elements, the old list contains only Orphans
    }/*from   w  w  w . j av  a  2  s  .c  o m*/
    if (oldElements.size() == 0) {
        return oldElements; // no old elements, so no Orphans neither
    }

    final EntityPersister entityPersister = session.getFactory().getEntityPersister(entityName);
    final Type idType = entityPersister.getIdentifierType();

    // create the collection holding the Orphans
    Collection<E> res = new ArrayList<E>(oldElements.unifiedComparator());

    // collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access
    Set<Serializable> currentIds = new HashSet<Serializable>();
    Set<E> currentSaving = new HashSet<E>(ReferenceEqualityComparator.getInstance());
    for (E current : currentElements) {
        if (current != null && ForeignKeys.isNotTransient(entityName, current, null, session)) {
            EntityEntry ee = session.getPersistenceContext().getEntry(current);
            if (ee != null && ee.getStatus() == Status.SAVING) {
                currentSaving.add(current);
            } else {
                Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, current,
                        session);
                currentIds.add(new TypedValue(idType, currentId));
            }
        }
    }

    // iterate over the *old* list
    for (E old : oldElements) {
        if (!currentSaving.contains(old)) {
            Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, old, session);
            if (!currentIds.contains(new TypedValue(idType, oldId))) {
                res.add(old);
            }
        }
    }

    return res;
}

From source file:org.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

License:Apache License

/**
 * 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/*w w  w . j  a va2s  .  c  o  m*/
 * @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);
}

From source file:to.etc.domui.hibernate.model.HibernateModelCopier.java

License:Open Source License

/**
 * Determine the object state using internal Hibernate data structures. Code was mostly stolen from {@link org.hibernate.event.internal.DefaultFlushEntityEventListener#dirtyCheck(FlushEntityEvent)} ()}
 *///from   www. jav a 2s.co  m
@Override
protected QPersistentObjectState getObjectState(QDataContext dc, Object instance) throws Exception {
    if (!(dc instanceof BuggyHibernateBaseContext))
        throw new IllegalArgumentException("The QDataContext type is not a Hibernate context");
    SessionImpl ses = (SessionImpl) ((BuggyHibernateBaseContext) dc).getSession();

    PersistenceContext pc = ses.getPersistenceContext(); // The root of all hibernate persistent data
    EntityEntry ee = pc.getEntry(instance);
    if (ee == null) {
        /*
         * Incredible but true: proxies are not stored as entries in the hibernate session - the backing objects
         * of the proxies are. This means that a prime invariant does NOT hold for proxies: the SAME database object
         * in the SAME object, where one is retrieved using a lazy association and the other through Session.load,
         * ARE NOT == (the same reference): the first one points to the proxy, the second one to the instance itself.
         * This is another huge design blunder and again a pitfall: you cannot use == EVEN WHEN IN A SINGLE SESSION!
         * This problem is most probably caused by the enormous design blunder that separates the proxy instance from
         * the actual instance.
         *
         * In here it means we need to check if the object is indeed a proxy, and retry with the original object.
         */
        if (instance instanceof HibernateProxy) { // Ohh Horror of horrors.
            HibernateProxy hp = (HibernateProxy) instance;
            Object ainstance = hp.getHibernateLazyInitializer().getImplementation();
            ee = pc.getEntry(ainstance);

            String clz = instance.getClass().getName();
            if (clz.contains("Relation"))
                System.out.println("DEBUG 2nd try for " + MetaManager.identify(instance));

            if (ee == null) {
                //-- DEBUG
                //               if(clz.contains("Relation")) {
                //                  //-- The failing relation record.
                //                  System.out.println("DEBUG Examining " + MetaManager.identify(instance));
                //
                //                  Object pk = MetaManager.getPrimaryKey(instance);
                //                  Map<Object, Object> eemap = pc.getEntityEntries();
                //                  for(Iterator<Object> it = ((IdentityMap) eemap).keyIterator(); it.hasNext();) {
                //                     Object ent = it.next();
                //                     if(ent.getClass().getName().contains("Relation")) {
                //                        //-- Probable match. Get PK's and compare
                //                        Object epk = MetaManager.getPrimaryKey(ent);
                //                        if(epk.equals(pk)) {
                //                           System.out.println("Primary key matches " + ent);
                //                           ee = pc.getEntry(ent);
                //                           System.out.println("EntityEntry: " + ee);
                //                        }
                //                     }
                //                  }
                //               }

                System.out.println("    state for " + MetaManager.identify(instance) + ": null in session");
                //-- ENDDEBUG

                return QPersistentObjectState.UNKNOWN;
            }
        }
    }
    if (null == ee)
        throw new IllegalStateException("current EntityEntry is null- that cannot happen?");

    System.out.println("    state for " + MetaManager.identify(instance) + ": exists=" + ee.isExistsInDatabase()
            + ", state=" + ee.getStatus());

    if (ee.getStatus() == Status.DELETED)
        return QPersistentObjectState.DELETED;
    if (!ee.isExistsInDatabase())
        return QPersistentObjectState.NEW;

    //-- Let's do a check.
    Object[] snapshot = ee.getLoadedState(); // Get snapshot @ load time
    if (snapshot == null)
        return QPersistentObjectState.NEW;
    Object[] values = ee.getPersister().getPropertyValues(instance); // Load current instance's values.

    //-- Delegate to any interceptor.
    int[] dirtyProperties = ses.getInterceptor().findDirty(instance, ee.getId(), values, snapshot,
            ee.getPersister().getPropertyNames(), ee.getPersister().getPropertyTypes());
    if (dirtyProperties == null) {
        //-- Do it ourselves.
        dirtyProperties = ee.getPersister().findDirty(values, snapshot, instance, ses);
    }
    return dirtyProperties == null || dirtyProperties.length == 0 ? QPersistentObjectState.PERSISTED
            : QPersistentObjectState.DIRTY;
}