Example usage for org.hibernate.context.internal ManagedSessionContext hasBind

List of usage examples for org.hibernate.context.internal ManagedSessionContext hasBind

Introduction

In this page you can find the example usage for org.hibernate.context.internal ManagedSessionContext hasBind.

Prototype

public static boolean hasBind(SessionFactory factory) 

Source Link

Document

Check to see if there is already a session associated with the current thread for the given session factory.

Usage

From source file:com.astonish.dropwizard.routing.hibernate.RoutingUnitOfWorkApplicationListenerTest.java

License:Apache License

@Test
public void bindsAndUnbindsTheSessionToTheManagedContext() throws Exception {
    doAnswer(new Answer<Object>() {
        @Override//www .  ja v a  2 s . c  o  m
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertThat(ManagedSessionContext.hasBind(sessionFactory)).isTrue();
            return null;
        }
    }).when(session).beginTransaction();

    execute();

    assertThat(ManagedSessionContext.hasBind(sessionFactory)).isFalse();
}

From source file:com.astonish.dropwizard.routing.hibernate.RoutingUnitOfWorkRequestDispatcherTest.java

License:Apache License

@Test
public void bindsAndUnbindsTheSessionToTheManagedContext() throws Exception {
    doAnswer(new Answer<Object>() {
        @Override/*from  ww  w .  j  a v a  2 s.co  m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertThat(ManagedSessionContext.hasBind(sessionFactory)).isTrue();
            return null;
        }
    }).when(underlying).dispatch(resource, context);

    dispatcher.dispatch(resource, context);

    assertThat(ManagedSessionContext.hasBind(sessionFactory)).isFalse();
}

From source file:com.vmware.photon.controller.api.common.db.TransactionalInterceptor.java

License:Open Source License

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    SessionFactory sessionFactory = sessionFactoryProvider.get();

    Session session;//ww  w .  j a va  2  s. c om
    if (ManagedSessionContext.hasBind(sessionFactory)) {
        session = sessionFactory.getCurrentSession();
    } else {
        session = sessionFactory.openSession();
        ManagedSessionContext.bind(session);
    }

    Transaction transaction = session.getTransaction();
    if (transaction.isActive()) {
        return invocation.proceed();
    }

    Stopwatch stopwatch = Stopwatch.createUnstarted();

    try {
        logger.trace("beginning transaction: {}", transaction);
        stopwatch.start();
        transaction.begin();
        Object result = invocation.proceed();
        transaction.commit();
        stopwatch.stop();
        logger.debug("committed: {}", transaction);
        return result;
    } catch (Throwable t) {
        logger.debug("rolling back: {}", transaction, t);
        transaction.rollback();
        transactionExceptions.mark();
        throw t;
    } finally {
        final long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        transactions.update(elapsedTime, TimeUnit.MILLISECONDS);
        ManagedSessionContext.unbind(sessionFactory);
        if (session.isOpen()) {
            session.close();
        }
        final long transactionTimeWarningThresholdInMilliseconds = 2000L;
        if (elapsedTime > transactionTimeWarningThresholdInMilliseconds) {
            logger.warn("Transaction {} took {} milliseconds", transaction, elapsedTime);
        }
    }
}

From source file:net.databinder.DBRequestCycleListener.java

License:Open Source License

/**
 * Closes all Hibernate sessions opened for this request. If a transaction has
 * not been committed, it will be rolled back before closing the session.
 * @see net.databinder.components.hib.DataForm#onSubmit()
 *//*from   w  w  w . ja va 2 s .com*/
@Override
public void onEndRequest(RequestCycle cycle) {
    for (Object key : keys) {
        SessionFactory sf = Databinder.getHibernateSessionFactory(key);
        if (ManagedSessionContext.hasBind(sf)) {
            closeSession(key);
            ManagedSessionContext.unbind(sf);
        }
    }
    log.debug("onEndRequest complete {}", cycle.getRequest().getUrl());
}

From source file:net.databinder.hib.Databinder.java

License:Open Source License

/**
 * Wraps SessionUnit callback in a temporary thread-bound Hibernate session from the keyed
 * factory if necessary. This is to be used outside of a regular a session-handling request cycle,
 * such as during application init or an external Web service request. 
 * The temporary session and transaction, if created, are closed after the callback returns and 
 * uncommited transactions are rolled back. Be careful of returning detached Hibernate 
 * objects that may not be fully loaded with data; consider using projections / scalar 
 * queries instead. <b>Note</b> This method uses a ManagedSessionContext. With JTA
 * or other forms of current session lookup a wrapping session will not be
 * detected and a new one will always be created. 
 * @param unit work to be performed in thread-bound session
 * @param key or null for the default factory
 * @see SessionUnit/*from   ww w  .ja  v a2 s  . c o m*/
 */
public static Object ensureSession(SessionUnit unit, Object key) {
    dataSessionRequested(key);
    SessionFactory sf = getHibernateSessionFactory(key);
    if (ManagedSessionContext.hasBind(sf))
        return unit.run(getHibernateSession(key));
    org.hibernate.Session sess = sf.openSession();
    try {
        sess.beginTransaction();
        ManagedSessionContext.bind(sess);
        return unit.run(sess);
    } finally {
        try {
            if (sess.getTransaction().isActive())
                sess.getTransaction().rollback();
        } finally {
            sess.close();
            ManagedSessionContext.unbind(sf);
        }
    }
}

From source file:org.jooby.internal.hbm.SessionProvider.java

License:Apache License

@Override
public Session get() {
    return ManagedSessionContext.hasBind(sf) ? sf.getCurrentSession() : sf.openSession();
}

From source file:org.jooby.internal.hbm.UnitOfWorkProvider.java

License:Apache License

@Override
public UnitOfWork get() {
    if (ManagedSessionContext.hasBind(sf)) {
        return new ChildUnitOfWork(sf.getCurrentSession());
    } else {//w w w.j av  a2s. c  o m
        return new RootUnitOfWork(sf.openSession());
    }
}