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.hibernate5.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  ww  w  .  j  av  a 2 s  .com

    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().getStatus() == TransactionStatus.ACTIVE) {
                    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.jpa.hibernate.HibernateNativeEntityManagerFactoryIntegrationTests.java

License:Apache License

@Test // SPR-16956
public void testReadOnly() {
    assertSame(FlushMode.AUTO, sessionFactory.getCurrentSession().getHibernateFlushMode());
    assertFalse(sessionFactory.getCurrentSession().isDefaultReadOnly());
    endTransaction();/*from   w w  w  .  j  a  v a  2 s . c  o  m*/

    this.transactionDefinition.setReadOnly(true);
    startNewTransaction();
    assertSame(FlushMode.MANUAL, sessionFactory.getCurrentSession().getHibernateFlushMode());
    assertTrue(sessionFactory.getCurrentSession().isDefaultReadOnly());
}

From source file:org.springframework.orm.jpa.vendor.HibernateJpaDialect.java

License:Apache License

protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException {
    FlushMode flushMode = session.getFlushMode();
    if (readOnly) {
        // We should suppress flushing for a read-only transaction.
        if (!flushMode.equals(FlushMode.MANUAL)) {
            session.setFlushMode(FlushMode.MANUAL);
            return flushMode;
        }/*  w  w  w  .j  a  v a  2  s .co  m*/
    } else {
        // We need AUTO or COMMIT for a non-read-only transaction.
        if (flushMode.lessThan(FlushMode.COMMIT)) {
            session.setFlushMode(FlushMode.AUTO);
            return flushMode;
        }
    }
    // No FlushMode change needed...
    return null;
}

From source file:org.squashtest.tm.service.internal.advancedsearch.IndexationServiceImpl.java

License:Open Source License

private FullTextSession getFullTextSession() {
    Session session = getCurrentSession();

    // get FullText session
    FullTextSession ftSession = Search.getFullTextSession(session);
    ftSession.setFlushMode(FlushMode.MANUAL);
    ftSession.setCacheMode(CacheMode.IGNORE);

    // Clear the lucene work queue to eliminate lazy init bug for batch processing.
    clearLuceneQueue(ftSession);//from   ww  w.j  ava 2  s  .  c  o m

    return ftSession;
}

From source file:org.squashtest.tm.service.internal.batchexport.ExportDao.java

License:Open Source License

private Session getStatelessSession() {
    Session s = em.unwrap(Session.class);
    s.setFlushMode(FlushMode.MANUAL);
    return s;
}

From source file:org.thelq.stackexchange.dbimport.DatabaseWriter.java

License:Apache License

public DatabaseWriter(DumpContainer container, String table) {
    this.table = table;
    this.container = container;
    session = container.getSessionFactory().openSession();
    session.setCacheMode(CacheMode.IGNORE);
    session.setFlushMode(FlushMode.MANUAL);
    session.beginTransaction();//from   w  ww  .  ja v  a2 s . co m
}

From source file:org.unitedinternet.cosmo.dao.hibernate.ContentDaoImpl.java

License:Apache License

public Set<ContentItem> loadChildren(CollectionItem collection, Date timestamp) {
    try {/*from   ww w . j  a  v a  2s.c  o  m*/
        Set<ContentItem> children = new HashSet<ContentItem>();
        Query query = null;

        // use custom HQL query that will eager fetch all associations
        if (timestamp == null) {
            query = getSession().getNamedQuery("contentItem.by.parent").setParameter("parent", collection);
        } else {
            query = getSession().getNamedQuery("contentItem.by.parent.timestamp")
                    .setParameter("parent", collection).setParameter("timestamp", timestamp);
        }
        query.setFlushMode(FlushMode.MANUAL);
        List results = query.list();
        for (Iterator it = results.iterator(); it.hasNext();) {
            ContentItem content = (ContentItem) it.next();
            initializeItem(content);
            children.add(content);
        }

        return children;

    } catch (HibernateException e) {
        getSession().clear();
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    }
}

From source file:org.unitedinternet.cosmo.dao.hibernate.ContentDaoImpl.java

License:Apache License

protected void checkForDuplicateICalUid(ICalendarItem item, CollectionItem parent) {

    // TODO: should icalUid be required?  Currrently its not and all
    // items created by the webui dont' have it.
    if (item.getIcalUid() == null) {
        return;/*from   www  .j av  a  2s. c  o  m*/
    }

    // ignore modifications
    if (item instanceof NoteItem && ((NoteItem) item).getModifies() != null) {
        return;
    }

    // Lookup item by parent/icaluid
    Query hibQuery = null;
    if (item instanceof NoteItem) {
        hibQuery = getSession().getNamedQuery("noteItemId.by.parent.icaluid")
                .setParameter("parentid", getBaseModelObject(parent).getId())
                .setParameter("icaluid", item.getIcalUid());
    } else {
        hibQuery = getSession().getNamedQuery("icalendarItem.by.parent.icaluid")
                .setParameter("parentid", getBaseModelObject(parent).getId())
                .setParameter("icaluid", item.getIcalUid());
    }
    hibQuery.setFlushMode(FlushMode.MANUAL);

    Long itemId = (Long) hibQuery.uniqueResult();

    // if icaluid is in use throw exception
    if (itemId != null) {
        // If the note is new, then its a duplicate icaluid
        if (getBaseModelObject(item).getId() == -1) {
            Item dup = (Item) getSession().load(HibItem.class, itemId);
            throw new IcalUidInUseException(
                    "iCal uid" + item.getIcalUid() + " already in use for collection " + parent.getUid(),
                    item.getUid(), dup.getUid());
        }
        // If the note exists and there is another note with the same
        // icaluid, then its a duplicate icaluid
        if (getBaseModelObject(item).getId().equals(itemId)) {
            Item dup = (Item) getSession().load(HibItem.class, itemId);
            throw new IcalUidInUseException(
                    "iCal uid" + item.getIcalUid() + " already in use for collection " + parent.getUid(),
                    item.getUid(), dup.getUid());
        }
    }
}

From source file:org.unitedinternet.cosmo.dao.hibernate.ItemDaoImpl.java

License:Apache License

public Item findItemByUid(String uid) {
    try {// ww  w  .  ja va2s. c  o m
        // prevent auto flushing when looking up item by uid
        getSession().setFlushMode(FlushMode.MANUAL);
        return (Item) getSession().byNaturalId(HibItem.class).using("uid", uid).load();
    } catch (HibernateException e) {
        getSession().clear();
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    }
}

From source file:org.unitedinternet.cosmo.dao.hibernate.ItemDaoImpl.java

License:Apache License

public Ticket findTicket(String key) {
    if (key == null) {
        throw new IllegalArgumentException("key cannot be null");
    }/* w ww.  j  a  v  a 2  s  . c om*/

    try {
        // prevent auto flushing when looking up ticket
        getSession().setFlushMode(FlushMode.MANUAL);
        Query hibQuery = getSession().getNamedQuery("ticket.by.key").setParameter("key", key);
        hibQuery.setCacheable(true);
        hibQuery.setFlushMode(FlushMode.MANUAL);
        return (Ticket) hibQuery.uniqueResult();
    } catch (HibernateException e) {
        getSession().clear();
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    }
}