Example usage for org.hibernate FlushMode AUTO

List of usage examples for org.hibernate FlushMode AUTO

Introduction

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

Prototype

FlushMode AUTO

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

Click Source Link

Document

The Session is sometimes flushed before query execution in order to ensure that queries never return stale state.

Usage

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

License:Apache License

@Test
public void testMergeWithEntityName() {
    TestBean tb = new TestBean();
    TestBean tbMerged = new TestBean();
    given(session.getFlushMode()).willReturn(FlushMode.AUTO);
    given(session.merge("myEntity", tb)).willReturn(tbMerged);
    assertSame(tbMerged, hibernateTemplate.merge("myEntity", tb));
}

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

License:Apache License

@Test
public void testDelete() {
    TestBean tb = new TestBean();
    given(session.getFlushMode()).willReturn(FlushMode.AUTO);
    hibernateTemplate.delete(tb);//from  w w  w. j ava 2 s . co  m
    verify(session).delete(tb);
}

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

License:Apache License

@Test
public void testDeleteWithEntityName() {
    TestBean tb = new TestBean();
    given(session.getFlushMode()).willReturn(FlushMode.AUTO);
    hibernateTemplate.delete("myEntity", tb);
    verify(session).delete("myEntity", tb);
}

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

License:Apache License

@Test
public void testDeleteAll() {
    TestBean tb1 = new TestBean();
    TestBean tb2 = new TestBean();
    given(session.getFlushMode()).willReturn(FlushMode.AUTO);
    List tbs = new ArrayList();
    tbs.add(tb1);//from  w  w w  .  j av a 2s  .  com
    tbs.add(tb2);
    hibernateTemplate.deleteAll(tbs);
    verify(session).delete(same(tb1));
    verify(session).delete(same(tb2));
}

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

License:Apache License

@Override
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 .  j  a  v a  2s  .c  o m

    Session session = null;

    try {
        if (txObject.getSessionHolder() == null
                || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            Interceptor entityInterceptor = getEntityInterceptor();
            Session newSession = (entityInterceptor != null
                    ? getSessionFactory().withOptions().interceptor(entityInterceptor).openSession()
                    : getSessionFactory().openSession());
            if (logger.isDebugEnabled()) {
                logger.debug("Opened new Session [" + 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 [" + session + "]");
            }
            Connection con = ((SessionImplementor) session).connection();
            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
            txObject.setPreviousIsolationLevel(previousIsolationLevel);
            if (this.allowResultAccessAfterCompletion && !txObject.isNewSession()) {
                int currentHoldability = con.getHoldability();
                if (currentHoldability != ResultSet.HOLD_CURSORS_OVER_COMMIT) {
                    txObject.setPreviousHoldability(currentHoldability);
                    con.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
                }
            }
        } 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' (the default for JDBC).");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Not preparing JDBC Connection of Hibernate Session [" + 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 (session.getFlushMode().equals(FlushMode.MANUAL)) {
                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 = ((SessionImplementor) 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.hibernate4.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionRollbackOnly() throws Exception {
    Connection con = mock(Connection.class);
    final SessionFactory sf = mock(SessionFactory.class);
    ImplementingSession session = mock(ImplementingSession.class);
    Transaction tx = mock(Transaction.class);

    given(sf.openSession()).willReturn(session);
    given(session.beginTransaction()).willReturn(tx);
    given(session.isOpen()).willReturn(true);
    given(session.getFlushMode()).willReturn(FlushMode.AUTO);
    given(session.isConnected()).willReturn(true);
    given(session.connection()).willReturn(con);

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

    tt.execute(new TransactionCallback() {
        @Override// w  ww.  ja  v  a 2s  . co  m
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            Session session = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession();
            session.flush();
            status.setRollbackOnly();
            return null;
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    verify(session).flush();
    verify(session).close();
    verify(tx).rollback();
}

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

License:Apache License

@Test
public void testParticipatingTransactionWithCommit() throws Exception {
    Connection con = mock(Connection.class);
    final SessionFactory sf = mock(SessionFactory.class);
    final ImplementingSession session = mock(ImplementingSession.class);
    Transaction tx = mock(Transaction.class);

    given(sf.openSession()).willReturn(session);
    given(session.beginTransaction()).willReturn(tx);
    given(session.isOpen()).willReturn(true);
    given(session.getFlushMode()).willReturn(FlushMode.AUTO);
    given(session.isConnected()).willReturn(true);
    given(session.connection()).willReturn(con);

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
        @Override/*from  w  w w  .  j  a  v a  2  s .c  o m*/
        protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb) {
            return sf;
        }
    };
    lsfb.afterPropertiesSet();
    final SessionFactory sfProxy = lsfb.getObject();

    PlatformTransactionManager tm = new HibernateTransactionManager(sfProxy);
    final TransactionTemplate tt = new TransactionTemplate(tm);
    final List l = new ArrayList();
    l.add("test");

    Object result = tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            return tt.execute(new TransactionCallback() {
                @Override
                public Object doInTransaction(TransactionStatus status) {
                    Session session = ((SessionHolder) TransactionSynchronizationManager.getResource(sf))
                            .getSession();
                    session.flush();
                    return l;
                }
            });
        }
    });
    assertTrue("Correct result list", result == l);

    verify(session).flush();
    verify(session).close();
    verify(tx).commit();
}

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

License:Apache License

@Test
public void testParticipatingTransactionWithRollback() throws Exception {
    Connection con = mock(Connection.class);
    final SessionFactory sf = mock(SessionFactory.class);
    ImplementingSession session = mock(ImplementingSession.class);
    Transaction tx = mock(Transaction.class);

    given(sf.openSession()).willReturn(session);
    given(session.beginTransaction()).willReturn(tx);
    given(session.isOpen()).willReturn(true);
    given(session.getFlushMode()).willReturn(FlushMode.AUTO);
    given(session.isConnected()).willReturn(true);
    given(session.connection()).willReturn(con);

    PlatformTransactionManager tm = new HibernateTransactionManager(sf);
    final TransactionTemplate tt = new TransactionTemplate(tm);
    try {//w  w  w . j a  va  2 s.c  o m
        tt.execute(new TransactionCallback() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                return tt.execute(new TransactionCallback() {
                    @Override
                    public Object doInTransaction(TransactionStatus status) {
                        throw new RuntimeException("application exception");
                    }
                });
            }
        });
        fail("Should have thrown RuntimeException");
    } catch (RuntimeException ex) {
        // expected
    }

    verify(session).close();
    verify(tx).rollback();
}

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

License:Apache License

@Test
public void testParticipatingTransactionWithRequiresNew() throws Exception {
    final SessionFactory sf = mock(SessionFactory.class);
    ImplementingSession session1 = mock(ImplementingSession.class);
    ImplementingSession session2 = mock(ImplementingSession.class);
    Connection con = mock(Connection.class);
    Transaction tx = mock(Transaction.class);

    given(sf.openSession()).willReturn(session1, session2);
    given(session1.beginTransaction()).willReturn(tx);
    given(session1.isOpen()).willReturn(true);
    given(session2.beginTransaction()).willReturn(tx);
    given(session2.isOpen()).willReturn(true);
    given(session2.getFlushMode()).willReturn(FlushMode.AUTO);
    given(session1.isConnected()).willReturn(true);
    given(session1.connection()).willReturn(con);
    given(session2.isConnected()).willReturn(true);
    given(session2.connection()).willReturn(con);

    PlatformTransactionManager tm = new HibernateTransactionManager(sf);
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    tt.execute(new TransactionCallback() {
        @Override/*from  ww w . jav  a 2 s  .  c  om*/
        public Object doInTransaction(TransactionStatus status) {
            final SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sf);
            assertTrue("Has thread session", holder != null);
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
            tt.execute(new TransactionCallback() {
                @Override
                public Object doInTransaction(TransactionStatus status) {
                    Session session = ((SessionHolder) TransactionSynchronizationManager.getResource(sf))
                            .getSession();
                    assertTrue("Not enclosing session", session != holder.getSession());
                    session.flush();
                    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
                    assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
                    return null;
                }
            });
            assertTrue("Same thread session as before",
                    holder.getSession() == ((SessionHolder) TransactionSynchronizationManager.getResource(sf))
                            .getSession());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
            return null;
        }
    });
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));

    verify(session2).flush();
    verify(session1).close();
    verify(session2).close();
    verify(tx, times(2)).commit();
}

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

License:Apache License

@Test
public void testParticipatingTransactionWithNotSupported() throws Exception {
    final SessionFactory sf = mock(SessionFactory.class);
    ImplementingSession session = mock(ImplementingSession.class);
    Connection con = mock(Connection.class);
    Transaction tx = mock(Transaction.class);

    given(sf.openSession()).willReturn(session);
    given(session.getSessionFactory()).willReturn(sf);
    given(session.beginTransaction()).willReturn(tx);
    given(session.isOpen()).willReturn(true);
    given(session.getFlushMode()).willReturn(FlushMode.AUTO);
    given(session.isConnected()).willReturn(true);
    given(session.connection()).willReturn(con);

    HibernateTransactionManager tm = new HibernateTransactionManager(sf);
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    tt.execute(new TransactionCallback() {
        @Override/*from   w  ww . j  a v  a 2  s .c o m*/
        public Object doInTransaction(TransactionStatus status) {
            SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sf);
            assertTrue("Has thread session", holder != null);
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
            tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
            tt.execute(new TransactionCallback() {
                @Override
                public Object doInTransaction(TransactionStatus status) {
                    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
                    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
                    assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
                    return null;
                }
            });
            assertTrue("Same thread session as before",
                    holder.getSession() == ((SessionHolder) TransactionSynchronizationManager.getResource(sf))
                            .getSession());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
            return null;
        }
    });
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));

    verify(session).close();
    verify(tx).commit();
}