Example usage for org.hibernate FlushMode MANUAL

List of usage examples for org.hibernate FlushMode MANUAL

Introduction

In this page you can find the example usage for org.hibernate FlushMode MANUAL.

Prototype

FlushMode MANUAL

To view the source code for org.hibernate FlushMode MANUAL.

Click Source Link

Document

The Session is only ever flushed when Session#flush is explicitly called by the application.

Usage

From source file:org.springframework.orm.hibernate3.HibernateTemplateTests.java

License:Apache License

@Test
public void testFlush() throws HibernateException {
    hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER);
    hibernateTemplate.flush();//from ww  w  .  ja va2  s.c  o m
    verify(session).setFlushMode(FlushMode.MANUAL);
    verify(session).flush();
    verify(session).close();
}

From source file:org.springframework.orm.hibernate3.HibernateTransactionManager.java

License:Apache License

@Override
@SuppressWarnings("deprecation")
protected void doBegin(Object transaction, TransactionDefinition definition) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

    if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
        throw new IllegalTransactionStateException(
                "Pre-bound JDBC Connection found! HibernateTransactionManager does not support "
                        + "running within DataSourceTransactionManager if told to manage the DataSource itself. "
                        + "It is recommended to use a single HibernateTransactionManager for all transactions "
                        + "on a single DataSource, no matter whether Hibernate or JDBC access.");
    }//from   w w  w  .ja v  a  2 s  .c  o  m

    Session session = null;

    try {
        if (txObject.getSessionHolder() == null
                || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            Interceptor entityInterceptor = getEntityInterceptor();
            Session newSession = (entityInterceptor != null ? getSessionFactory().openSession(entityInterceptor)
                    : getSessionFactory().openSession());
            if (logger.isDebugEnabled()) {
                logger.debug("Opened new Session [" + SessionFactoryUtils.toString(newSession)
                        + "] for Hibernate transaction");
            }
            txObject.setSession(newSession);
        }

        session = txObject.getSessionHolder().getSession();

        if (this.prepareConnection && isSameConnectionForEntireSession(session)) {
            // We're allowed to change the transaction settings of the JDBC Connection.
            if (logger.isDebugEnabled()) {
                logger.debug("Preparing JDBC Connection of Hibernate Session ["
                        + SessionFactoryUtils.toString(session) + "]");
            }
            Connection con = session.connection();
            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
            txObject.setPreviousIsolationLevel(previousIsolationLevel);
        } else {
            // Not allowed to change the transaction settings of the JDBC Connection.
            if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
                // We should set a specific isolation level but are not allowed to...
                throw new InvalidIsolationLevelException(
                        "HibernateTransactionManager is not allowed to support custom isolation levels: "
                                + "make sure that its 'prepareConnection' flag is on (the default) and that the "
                                + "Hibernate connection release mode is set to 'on_close' (SpringTransactionFactory's default). "
                                + "Make sure that your LocalSessionFactoryBean actually uses SpringTransactionFactory: Your "
                                + "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Not preparing JDBC Connection of Hibernate Session ["
                        + SessionFactoryUtils.toString(session) + "]");
            }
        }

        if (definition.isReadOnly() && txObject.isNewSession()) {
            // Just set to MANUAL in case of a new Session for this transaction.
            session.setFlushMode(FlushMode.MANUAL);
        }

        if (!definition.isReadOnly() && !txObject.isNewSession()) {
            // We need AUTO or COMMIT for a non-read-only transaction.
            FlushMode flushMode = session.getFlushMode();
            if (flushMode.lessThan(FlushMode.COMMIT)) {
                session.setFlushMode(FlushMode.AUTO);
                txObject.getSessionHolder().setPreviousFlushMode(flushMode);
            }
        }

        Transaction hibTx;

        // Register transaction timeout.
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            // Use Hibernate's own transaction timeout mechanism on Hibernate 3.1+
            // Applies to all statements, also to inserts, updates and deletes!
            hibTx = session.getTransaction();
            hibTx.setTimeout(timeout);
            hibTx.begin();
        } else {
            // Open a plain Hibernate transaction without specified timeout.
            hibTx = session.beginTransaction();
        }

        // Add the Hibernate transaction to the session holder.
        txObject.getSessionHolder().setTransaction(hibTx);

        // Register the Hibernate Session's JDBC Connection for the DataSource, if set.
        if (getDataSource() != null) {
            Connection con = session.connection();
            ConnectionHolder conHolder = new ConnectionHolder(con);
            if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
                conHolder.setTimeoutInSeconds(timeout);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]");
            }
            TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);
            txObject.setConnectionHolder(conHolder);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewSessionHolder()) {
            TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder());
        }
        txObject.getSessionHolder().setSynchronizedWithTransaction(true);
    }

    catch (Throwable ex) {
        if (txObject.isNewSession()) {
            try {
                if (session.getTransaction().isActive()) {
                    session.getTransaction().rollback();
                }
            } catch (Throwable ex2) {
                logger.debug("Could not rollback Session after failed transaction begin", ex);
            } finally {
                SessionFactoryUtils.closeSession(session);
                txObject.setSessionHolder(null);
            }
        }
        throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);
    }
}

From source file:org.springframework.orm.hibernate3.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionCommitWithEarlyFlush() throws Exception {
    final DataSource ds = mock(DataSource.class);
    Connection con = mock(Connection.class);
    final SessionFactory sf = mock(SessionFactory.class);
    final Session session = mock(Session.class);
    Transaction tx = mock(Transaction.class);
    Query query = mock(Query.class);

    final List list = new ArrayList();
    list.add("test");
    given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
    given(sf.openSession()).willReturn(session);
    given(session.getTransaction()).willReturn(tx);
    given(session.connection()).willReturn(con);
    given(session.isOpen()).willReturn(true);
    given(session.createQuery("some query string")).willReturn(query);
    given(query.list()).willReturn(list);
    given(session.getFlushMode()).willReturn(FlushMode.AUTO);
    given(session.isConnected()).willReturn(true);

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
        @Override/*  w ww.j a  v  a 2  s  . co  m*/
        protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
            return sf;
        }
    };
    lsfb.afterPropertiesSet();
    final SessionFactory sfProxy = lsfb.getObject();

    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setJdbcExceptionTranslator(new SQLStateSQLExceptionTranslator());
    tm.setSessionFactory(sfProxy);
    tm.setDataSource(ds);
    tm.setEarlyFlushBeforeCommit(true);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    tt.setTimeout(10);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    Object result = tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sfProxy));
            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
            HibernateTemplate ht = new HibernateTemplate(sfProxy);
            return ht.find("some query string");
        }
    });
    assertTrue("Correct result list", result == list);

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
    InOrder ordered = inOrder(con);
    ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    verify(tx).setTimeout(10);
    verify(tx).begin();
    verify(session).flush();
    verify(session).setFlushMode(FlushMode.MANUAL);
    verify(tx).commit();
    verify(session).close();
}

From source file:org.springframework.orm.hibernate3.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionWithPropagationSupports() throws Exception {
    final SessionFactory sf = mock(SessionFactory.class);
    final Session session = mock(Session.class);

    given(sf.openSession()).willReturn(session);
    given(session.getSessionFactory()).willReturn(sf);
    given(session.getFlushMode()).willReturn(FlushMode.MANUAL);

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
        @Override//from  ww w . j  a v  a2  s . co  m
        protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
            return sf;
        }
    };
    lsfb.afterPropertiesSet();
    final SessionFactory sfProxy = lsfb.getObject();

    PlatformTransactionManager tm = new HibernateTransactionManager(sfProxy);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));

    tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
            assertTrue("Is not new transaction", !status.isNewTransaction());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            HibernateTemplate ht = new HibernateTemplate(sfProxy);
            ht.setFlushMode(HibernateTemplate.FLUSH_EAGER);
            ht.execute(new HibernateCallback() {
                @Override
                public Object doInHibernate(org.hibernate.Session session) {
                    return null;
                }
            });
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sfProxy));
            return null;
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
    InOrder ordered = inOrder(session);
    ordered.verify(session).setFlushMode(FlushMode.AUTO);
    ordered.verify(session).flush();
    ordered.verify(session).setFlushMode(FlushMode.MANUAL);
    ordered.verify(session).close();
}

From source file:org.springframework.orm.hibernate3.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionWithPropagationSupportsAndCurrentSession() throws Exception {
    final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
    final Session session = mock(Session.class);

    given(sf.openSession()).willReturn(session);
    given(session.getSessionFactory()).willReturn(sf);
    given(session.getFlushMode()).willReturn(FlushMode.MANUAL);

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
        @Override//from  w  w w .  j ava 2 s . c  o  m
        protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
            return sf;
        }
    };
    lsfb.afterPropertiesSet();
    final SessionFactory sfProxy = lsfb.getObject();

    PlatformTransactionManager tm = new HibernateTransactionManager(sfProxy);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));

    tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
            assertTrue("Is not new transaction", !status.isNewTransaction());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            Session session = new SpringSessionContext(sf).currentSession();
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sfProxy));
            session.flush();
            return null;
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
    InOrder ordered = inOrder(session);
    ordered.verify(session).flush();
    ordered.verify(session).close();
}

From source file:org.springframework.orm.hibernate3.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionCommitWithReadOnly() throws Exception {
    Connection con = mock(Connection.class);
    final SessionFactory sf = mock(SessionFactory.class);
    Session session = mock(Session.class);
    Transaction tx = mock(Transaction.class);
    Query query = mock(Query.class);

    final List list = new ArrayList();
    list.add("test");
    given(sf.openSession()).willReturn(session);
    given(session.beginTransaction()).willReturn(tx);
    given(session.connection()).willReturn(con);
    given(session.isOpen()).willReturn(true);
    given(session.createQuery("some query string")).willReturn(query);
    given(query.list()).willReturn(list);
    given(session.isConnected()).willReturn(true);
    given(con.isReadOnly()).willReturn(true);

    HibernateTransactionManager tm = new HibernateTransactionManager(sf);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setReadOnly(true);//w  ww .  j a v a  2s. c  om
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    Object result = tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
            HibernateTemplate ht = new HibernateTemplate(sf);
            return ht.find("some query string");
        }
    });
    assertTrue("Correct result list", result == list);

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    verify(session).setFlushMode(FlushMode.MANUAL);
    verify(con).setReadOnly(true);
    verify(tx).commit();
    verify(con).setReadOnly(false);
    verify(session).close();
}

From source file:org.springframework.orm.hibernate3.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionCommitWithPreBound() throws Exception {
    final DataSource ds = mock(DataSource.class);
    Connection con = mock(Connection.class);
    final SessionFactory sf = mock(SessionFactory.class);
    final Session session = mock(Session.class);
    Transaction tx = mock(Transaction.class);

    given(session.beginTransaction()).willReturn(tx);
    given(session.isOpen()).willReturn(true);
    given(session.getFlushMode()).willReturn(FlushMode.MANUAL);
    given(session.connection()).willReturn(con);
    given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
    given(session.isConnected()).willReturn(true);

    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf);/*  w  w  w.  j  a  v  a2s . c o  m*/
    tm.setDataSource(ds);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    final List l = new ArrayList();
    l.add("test");
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
    TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));

    Object result = tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
            SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf);
            assertTrue("Has thread transaction", sessionHolder.getTransaction() != null);
            HibernateTemplate ht = new HibernateTemplate(sf);
            ht.setExposeNativeSession(true);
            return ht.executeFind(new HibernateCallback() {
                @Override
                public Object doInHibernate(org.hibernate.Session sess) throws HibernateException {
                    assertEquals(session, sess);
                    return l;
                }
            });
        }
    });
    assertTrue("Correct result list", result == l);

    assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf);
    assertTrue("Hasn't thread transaction", sessionHolder.getTransaction() == null);
    TransactionSynchronizationManager.unbindResource(sf);
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    InOrder ordered = inOrder(session, con);
    ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    ordered.verify(session).setFlushMode(FlushMode.AUTO);
    ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    ordered.verify(session).setFlushMode(FlushMode.MANUAL);
    verify(tx).commit();
    verify(session).disconnect();
}

From source file:org.springframework.orm.hibernate3.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionRollbackWithPreBound() throws Exception {
    final DataSource ds = mock(DataSource.class);
    Connection con = mock(Connection.class);
    final SessionFactory sf = mock(SessionFactory.class);
    final Session session = mock(Session.class);
    final Transaction tx1 = mock(Transaction.class);
    final Transaction tx2 = mock(Transaction.class);

    given(session.beginTransaction()).willReturn(tx1, tx2);
    given(session.isOpen()).willReturn(true);
    given(session.getFlushMode()).willReturn(FlushMode.MANUAL);
    given(session.isConnected()).willReturn(true);
    given(session.connection()).willReturn(con);

    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf);//  w  ww  .j a v  a  2s  .co m
    tm.setDataSource(ds);
    final TransactionTemplate tt = new TransactionTemplate(tm);
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
    TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));

    try {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
                assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
                SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf);
                assertEquals(tx1, sessionHolder.getTransaction());
                tt.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    public void doInTransactionWithoutResult(TransactionStatus status) {
                        status.setRollbackOnly();
                        HibernateTemplate ht = new HibernateTemplate(sf);
                        ht.setExposeNativeSession(true);
                        ht.execute(new HibernateCallback() {
                            @Override
                            public Object doInHibernate(org.hibernate.Session sess) throws HibernateException {
                                assertEquals(session, sess);
                                return null;
                            }
                        });
                    }
                });
            }
        });
        fail("Should have thrown UnexpectedRollbackException");
    } catch (UnexpectedRollbackException ex) {
        // expected
    }

    assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf);
    assertTrue("Hasn't thread transaction", sessionHolder.getTransaction() == null);
    assertTrue("Not marked rollback-only", !sessionHolder.isRollbackOnly());

    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
            SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf);
            assertEquals(tx2, sessionHolder.getTransaction());
            HibernateTemplate ht = new HibernateTemplate(sf);
            ht.setExposeNativeSession(true);
            ht.execute(new HibernateCallback() {
                @Override
                public Object doInHibernate(org.hibernate.Session sess) throws HibernateException {
                    assertEquals(session, sess);
                    return null;
                }
            });
        }
    });

    assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
    assertTrue("Hasn't thread transaction", sessionHolder.getTransaction() == null);
    TransactionSynchronizationManager.unbindResource(sf);
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    verify(tx1).rollback();
    verify(tx2).commit();
    InOrder ordered = inOrder(session);
    ordered.verify(session).clear();
    ordered.verify(session).setFlushMode(FlushMode.AUTO);
    ordered.verify(session).setFlushMode(FlushMode.MANUAL);
    ordered.verify(session).disconnect();
}

From source file:org.springframework.orm.hibernate3.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionRollbackWithHibernateManagedSession() throws Exception {
    final SessionFactory sf = mock(SessionFactory.class);
    final Session session = mock(Session.class);
    final Transaction tx1 = mock(Transaction.class);
    final Transaction tx2 = mock(Transaction.class);

    given(sf.getCurrentSession()).willReturn(session);
    given(session.isOpen()).willReturn(true);
    given(session.getTransaction()).willReturn(tx1, tx2);
    given(session.beginTransaction()).willReturn(tx1, tx2);
    given(session.getFlushMode()).willReturn(FlushMode.MANUAL);

    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf);/*from  ww w.jav a 2  s  .  c  om*/
    tm.setPrepareConnection(false);
    tm.setHibernateManagedSession(true);
    final TransactionTemplate tt = new TransactionTemplate(tm);

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));

    try {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
                tt.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    public void doInTransactionWithoutResult(TransactionStatus status) {
                        status.setRollbackOnly();
                        HibernateTemplate ht = new HibernateTemplate(sf);
                        ht.setAllowCreate(false);
                        ht.setExposeNativeSession(true);
                        ht.execute(new HibernateCallback() {
                            @Override
                            public Object doInHibernate(org.hibernate.Session sess) throws HibernateException {
                                assertEquals(session, sess);
                                return null;
                            }
                        });
                    }
                });
            }
        });
        fail("Should have thrown UnexpectedRollbackException");
    } catch (UnexpectedRollbackException ex) {
        // expected
    }

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));

    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            HibernateTemplate ht = new HibernateTemplate(sf);
            ht.setAllowCreate(false);
            ht.setExposeNativeSession(true);
            ht.execute(new HibernateCallback() {
                @Override
                public Object doInHibernate(org.hibernate.Session sess) throws HibernateException {
                    assertEquals(session, sess);
                    return null;
                }
            });
        }
    });

    verify(tx1).rollback();
    verify(tx2).commit();
    InOrder ordered = inOrder(session);
    ordered.verify(session).setFlushMode(FlushMode.AUTO);
    ordered.verify(session).setFlushMode(FlushMode.MANUAL);
}

From source file:org.springframework.orm.hibernate3.SessionFactoryUtils.java

License:Apache License

/**
 * Get a Hibernate Session for the given SessionFactory. Is aware of and will
 * return any existing corresponding Session bound to the current thread, for
 * example when using {@link HibernateTransactionManager}. Will create a new
 * Session otherwise, if "allowCreate" is {@code true}.
 * <p>Same as {@link #getSession}, but throwing the original HibernateException.
 * @param sessionFactory Hibernate SessionFactory to create the session with
 * @param entityInterceptor Hibernate entity interceptor, or {@code null} if none
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be {@code null})
 * @param allowCreate whether a non-transactional Session should be created
 * when no transactional Session can be found for the current thread
 * @return the Hibernate Session// w w w.j a  va 2s  .  co m
 * @throws HibernateException if the Session couldn't be created
 * @throws IllegalStateException if no thread-bound Session found and
 * "allowCreate" is {@code false}
 */
private static Session doGetSession(SessionFactory sessionFactory, Interceptor entityInterceptor,
        SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate)
        throws HibernateException, IllegalStateException {

    Assert.notNull(sessionFactory, "No SessionFactory specified");

    Object resource = TransactionSynchronizationManager.getResource(sessionFactory);
    if (resource instanceof Session) {
        return (Session) resource;
    }
    SessionHolder sessionHolder = (SessionHolder) resource;
    if (sessionHolder != null && !sessionHolder.isEmpty()) {
        // pre-bound Hibernate Session
        Session session = null;
        if (TransactionSynchronizationManager.isSynchronizationActive()
                && sessionHolder.doesNotHoldNonDefaultSession()) {
            // Spring transaction management is active ->
            // register pre-bound Session with it for transactional flushing.
            session = sessionHolder.getValidatedSession();
            if (session != null && !sessionHolder.isSynchronizedWithTransaction()) {
                logger.debug("Registering Spring transaction synchronization for existing Hibernate Session");
                TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(
                        sessionHolder, sessionFactory, jdbcExceptionTranslator, false));
                sessionHolder.setSynchronizedWithTransaction(true);
                // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
                // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
                FlushMode flushMode = session.getFlushMode();
                if (flushMode.lessThan(FlushMode.COMMIT)
                        && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                    session.setFlushMode(FlushMode.AUTO);
                    sessionHolder.setPreviousFlushMode(flushMode);
                }
            }
        } else {
            // No Spring transaction management active -> try JTA transaction synchronization.
            session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator);
        }
        if (session != null) {
            return session;
        }
    }

    logger.debug("Opening Hibernate Session");
    Session session = (entityInterceptor != null ? sessionFactory.openSession(entityInterceptor)
            : sessionFactory.openSession());

    // Use same Session for further Hibernate actions within the transaction.
    // Thread object will get removed by synchronization at transaction completion.
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        // We're within a Spring-managed transaction, possibly from JtaTransactionManager.
        logger.debug("Registering Spring transaction synchronization for new Hibernate Session");
        SessionHolder holderToUse = sessionHolder;
        if (holderToUse == null) {
            holderToUse = new SessionHolder(session);
        } else {
            holderToUse.addSession(session);
        }
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.MANUAL);
        }
        TransactionSynchronizationManager.registerSynchronization(
                new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != sessionHolder) {
            TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
        }
    } else {
        // No Spring transaction management active -> try JTA transaction synchronization.
        registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder);
    }

    // Check whether we are allowed to return the Session.
    if (!allowCreate && !isSessionTransactional(session, sessionFactory)) {
        closeSession(session);
        throw new IllegalStateException("No Hibernate Session bound to thread, "
                + "and configuration does not allow creation of non-transactional one here");
    }

    return session;
}