Example usage for org.hibernate.internal SessionImpl getPersistenceContext

List of usage examples for org.hibernate.internal SessionImpl getPersistenceContext

Introduction

In this page you can find the example usage for org.hibernate.internal SessionImpl getPersistenceContext.

Prototype

@Override
    public PersistenceContext getPersistenceContext() 

Source Link

Usage

From source file:br.gov.jfrj.siga.model.Objeto.java

License:Open Source License

private static void cascadeOrphans(Objeto base, PersistentCollection persistentCollection, boolean willBeSaved)
        throws UnexpectedException {
    SessionImpl session = ((SessionImpl) em().getDelegate());
    PersistenceContext pc = session.getPersistenceContext();
    CollectionEntry ce = pc.getCollectionEntry(persistentCollection);

    if (ce != null) {
        CollectionPersister cp = ce.getLoadedPersister();
        if (cp != null) {
            Type ct = cp.getElementType();
            if (ct instanceof EntityType) {
                EntityEntry entry = pc.getEntry(base);
                String entityName = entry.getEntityName();
                entityName = ((EntityType) ct).getAssociatedEntityName(session.getFactory());
                if (ce.getSnapshot() != null) {
                    Collection orphans = ce.getOrphans(entityName, persistentCollection);
                    for (Object o : orphans) {
                        saveAndCascadeIfObjeto(o, willBeSaved);
                    }//w  ww  . ja va 2  s .  c om
                }
            }
        }
    }
}

From source file:to.etc.domui.hibernate.generic.HibernateLongSessionContext.java

License:Open Source License

@Override
public void conversationDestroyed(AbstractConversationContext cc) throws Exception {
    if (m_session == null || !m_session.isConnected())
        return;/*from  ww  w . jav  a  2  s. c o m*/
    try {
        setConversationInvalid("Conversation was destroyed");
        setIgnoreClose(false);
        SessionImpl sim = (SessionImpl) m_session;
        StatefulPersistenceContext spc = (StatefulPersistenceContext) sim.getPersistenceContext();
        Map<?, ?> flups = spc.getEntitiesByKey();
        if (LOG.isDebugEnabled())
            LOG.debug("Hibernate: closing (destroying) session " + System.identityHashCode(m_session)
                    + " containing " + flups.size() + " persisted instances");
        if (m_session.getTransaction().isActive())
            m_session.getTransaction().rollback();
        close();
    } catch (Exception x) {
        LOG.info("Exception during conversation destroy: " + x, x);
    }
}

From source file:to.etc.domui.hibernate.generic.HibernateLongSessionContext.java

License:Open Source License

@Override
public void conversationDetached(AbstractConversationContext cc) throws Exception {
    if (m_session == null || !m_session.isConnected())
        return;/*  w w  w  .  jav a2 s  . c om*/
    setConversationInvalid("Conversation is detached");
    SessionImpl sim = (SessionImpl) m_session;
    StatefulPersistenceContext spc = (StatefulPersistenceContext) sim.getPersistenceContext();
    Map<?, ?> flups = spc.getEntitiesByKey();
    if (LOG.isDebugEnabled())
        LOG.debug("Hibernate: disconnecting session " + System.identityHashCode(m_session) + " containing "
                + flups.size() + " persisted instances");

    /*
     * 20180829 jal Hibernate 5.2 clears its session cache during rollback, so that all
     * entities disappear. There is no real way in its code to prevent that. As an experiment
     * do not manipulate Hibernate's transaction here; just disconnect the connection.
     */
    //if(m_session.getTransaction().isActive())
    //   m_session.getTransaction().rollback();
    m_session.disconnect(); // Disconnect the dude.
    //      if(m_session.isConnected())
    //         System.out.println("Session connected after disconnect ;-)");
}

From source file:to.etc.domui.hibernate.generic.HibernateReattachingDataContext.java

License:Open Source License

@Override
public void conversationDetached(AbstractConversationContext cc) throws Exception {
    if (m_session == null)
        return;/*w  ww . jav  a 2  s .  co m*/

    /*
     * jal 20080822 Attempt to fix org.hibernate.NonUniqueObjectException by saving all objects currently in the session and
     * reattaching them automagically at conversation attach time.
     */
    long ts = System.nanoTime();
    SessionImpl sim = (SessionImpl) m_session;
    StatefulPersistenceContext spc = (StatefulPersistenceContext) sim.getPersistenceContext();
    Map<?, ?> flups = spc.getEntitiesByKey();
    m_hibernatePersistedObjects.clear();
    for (Object ent : flups.values()) {
        //         System.out.println(">> Got entity: "+ent);
        m_hibernatePersistedObjects.add(ent);
    }
    ts = System.nanoTime() - ts;
    if (LOG.isDebugEnabled())
        LOG.debug("hib: saved " + flups.size() + " persisted objects in the conversation for reattachment in "
                + StringTool.strNanoTime(ts));
    close();
}

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)} ()}
 *///  w ww .  j a v a 2 s  .  c  o  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;
}