Example usage for org.hibernate FlushMode COMMIT

List of usage examples for org.hibernate FlushMode COMMIT

Introduction

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

Prototype

FlushMode COMMIT

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

Click Source Link

Document

The Session is flushed when Transaction#commit is called.

Usage

From source file:org.opentox.toxotis.persistence.db.RegisterTool.java

License:Open Source License

public void storeErrorReport(ErrorReport er) {
    Session session = getSession();/*from w  ww . ja  va2  s .com*/
    Transaction transaction = null;
    session.setFlushMode(FlushMode.COMMIT);
    try {
        transaction = session.beginTransaction();
        session.saveOrUpdate(er);
        transaction.commit();
    } catch (RuntimeException ex) {
        logger.warn("Storage of Error Report failed. Logging the corresponding exception for details", ex);
        try {
            if (transaction != null) {
                transaction.rollback();
            }
        } catch (Throwable rte) {
            logger.error("Cannot rollback", rte);
        }
        throw ex;
    } finally {
        closeSession(session);
    }
}

From source file:org.opentox.toxotis.persistence.db.RegisterTool.java

License:Open Source License

public void storeMetaData(MetaInfo meta) {
    Session session = getSession();//from  w w  w .  j  av  a2s  . c  o m
    Transaction transaction = null;
    session.setFlushMode(FlushMode.COMMIT);
    try {
        //TODO: Code for storing meta data!
    } catch (RuntimeException ex) {
        logger.warn("Storage of MetaInfo failed. Logging the corresponding exception for details", ex);
        try {
            if (transaction != null) {
                transaction.rollback();
            }
        } catch (Throwable rte) {
            logger.error("Cannot rollback", rte);
        }
        throw ex;
    } finally {
        closeSession(session);
    }

}

From source file:org.opentox.toxotis.persistence.db.RegisterTool.java

License:Open Source License

public synchronized void storeTask(Task task) {
    Session session = getSession();//from w w  w  . j av  a 2s .c  o m
    Transaction transaction = null;
    session.setFlushMode(FlushMode.COMMIT);

    try {
        transaction = session.beginTransaction();
        User createdBy = task.getCreatedBy();
        if (createdBy != null) {
            session.saveOrUpdate(createdBy);
            session.flush();
            session.evict(createdBy);
        }
        ErrorReport er = task.getErrorReport();
        if (er != null) {
            session.saveOrUpdate(er);
            session.flush();
            session.evict(er);
        }
        session.saveOrUpdate(task);
        session.flush();
        transaction.commit();

    } catch (RuntimeException ex) {
        logger.warn("Storage of Task failed. Logging the corresponding exception for details.", ex);
        try {
            if (transaction != null) {
                transaction.rollback();
            }
        } catch (Throwable rte) {
            logger.error("Cannot rollback", rte);
        }
        throw ex;
    } finally {
        closeSession(session);
    }
}

From source file:org.openvpms.component.business.dao.hibernate.im.IMObjectDAOHibernate.java

License:Open Source License

/**
 * Returns the current hibernate session.
 * <p>/* w ww  .j  a  v a 2 s  .  c  o m*/
 * This ensures that the session flush mode is {@link FlushMode#COMMIT} to ensure that ids and versions get reverted
 * correctly if the transaction rolls back.
 *
 * @return the current hibernate session
 */
private Session getSession() {
    Session session = factory.getCurrentSession();
    session.setHibernateFlushMode(FlushMode.COMMIT);
    return session;
}

From source file:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

boolean isKnownInDB(URI location, String queueName) {
    boolean known = false;

    Session session = null;/*from   w w  w  . j  ava2s .c o m*/
    Transaction transaction = null;
    try {
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        Query query = session
                .createQuery(
                        String.format("SELECT count(location) FROM %s as cmd WHERE location = ?", queueName))
                .setParameter(0, location);
        Long result = (Long) query.setReadOnly(true).uniqueResult();
        known = (result != null && result.longValue() > 0);

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error(String.format("Unexpected '%s' while testing if location '%s' is known.",
                e.getClass().getName(), location.toASCIIString()), e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return known;
}

From source file:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

private List<ICommand> fetchNextCommands(int limit) {
    List<ICommand> result = new ArrayList<ICommand>();

    Session session = null;/*w  w  w . j  a v a  2  s  . c  o  m*/
    Transaction transaction = null;
    try {
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        Query query = session.createQuery("FROM EnqueuedCommand as cmd");
        query.setFetchSize(limit); // this is important for derby because there is no limit support
        query.setMaxResults(limit); // restricting number of returned results
        query.setReadOnly(true); // read-only query
        ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);

        final Key key = new Key();
        final DynamicBloomFilter bloomFilter = this.bloomFilter;
        final Cache urlExistsCache = this.urlExistsCache;

        // loop through the available commands
        while (sr.next() && result.size() < limit) {
            ICommand cmd = (ICommand) sr.get()[0];

            /* mark command as enqueued */
            session.delete("EnqueuedCommand", cmd);
            session.saveOrUpdate("CrawledCommand", cmd);

            // add command-location into caches
            key.set(cmd.getLocation().toString().getBytes(UTF8), 1.0);
            bloomFilter.add(key);
            Element element = new Element(cmd.getLocation(), null);
            urlExistsCache.put(element);

            result.add(cmd);
        }
        sr.close();

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error("Error while fetching commands", e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return result;
}

From source file:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

/**
 * First queries the DB to remove all known locations from the list and then updates
 * it with the new list./*  w  w  w.  j a v a  2  s. co m*/
 * 
 * @param profileID the ID of the {@link ICommandProfile}, newly created 
 * commands should belong to
 * @param depth depth of the new {@link ICommand} 
 * @param locations the locations to add to the DB
 * @return the number of known locations in the given list
 */
int storeUnknownLocations(int profileID, int depth, LinkedList<URI> locations) {
    if (locations == null || locations.size() == 0)
        return 0;

    int known = 0;
    Session session = null;
    Transaction transaction = null;
    try {
        // open session and transaction
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        // check the cache for URL existance and put the ones not known to the
        // cache into another list and remove them from the list which is checked
        // against the DB below
        known += storeUnknownInDoubleCache(profileID, depth, locations, session);

        // check which URLs are already known against the DB
        if (locations.size() > 0)
            known += storeUnknownInDB(profileID, depth, locations, session, 10);

        transaction.commit();

        // signal writer that a new URL is available
        this.writerThread.signalNewDbData();

        return known;
    } catch (Throwable e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error(String.format("Unexpected '%s' while writing %d new commands to db.",
                e.getClass().getName(), Integer.valueOf(locations.size())), e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return 0;
}

From source file:org.springframework.beans.factory.xml.XmlBeanCollectionTests.java

License:Apache License

public void testEnumSetFactory() throws Exception {
    XmlBeanFactory xbf = new XmlBeanFactory(new ClassPathResource("collections.xml", getClass()));
    Set set = (Set) xbf.getBean("enumSetFactory");
    assertTrue(set.size() == 2);/*from  w  w  w.  j  a v  a 2s  .  c o  m*/
    assertTrue(set.contains(FlushMode.NEVER));
    assertTrue(set.contains(FlushMode.COMMIT));
}

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

License:Apache License

/**
 * Apply the flush mode that's been specified for this accessor
 * to the given Session./*from w w w.  j a  v  a 2s.c  o  m*/
 * @param session the current Hibernate Session
 * @param existingTransaction if executing within an existing transaction
 * @return the previous flush mode to restore after the operation,
 * or {@code null} if none
 * @see #setFlushMode
 * @see org.hibernate.Session#setFlushMode
 */
protected FlushMode applyFlushMode(Session session, boolean existingTransaction) {
    if (getFlushMode() == FLUSH_NEVER) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (!previousFlushMode.lessThan(FlushMode.COMMIT)) {
                session.setFlushMode(FlushMode.MANUAL);
                return previousFlushMode;
            }
        } else {
            session.setFlushMode(FlushMode.MANUAL);
        }
    } else if (getFlushMode() == FLUSH_EAGER) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (!previousFlushMode.equals(FlushMode.AUTO)) {
                session.setFlushMode(FlushMode.AUTO);
                return previousFlushMode;
            }
        } else {
            // rely on default FlushMode.AUTO
        }
    } else if (getFlushMode() == FLUSH_COMMIT) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (previousFlushMode.equals(FlushMode.AUTO) || previousFlushMode.equals(FlushMode.ALWAYS)) {
                session.setFlushMode(FlushMode.COMMIT);
                return previousFlushMode;
            }
        } else {
            session.setFlushMode(FlushMode.COMMIT);
        }
    } else if (getFlushMode() == FLUSH_ALWAYS) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (!previousFlushMode.equals(FlushMode.ALWAYS)) {
                session.setFlushMode(FlushMode.ALWAYS);
                return previousFlushMode;
            }
        } else {
            session.setFlushMode(FlushMode.ALWAYS);
        }
    }
    return null;
}

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

License:Apache License

@Test
public void testInterceptorWithThreadBoundAndFlushCommit() {
    given(session.isOpen()).willReturn(true);
    given(session.getFlushMode()).willReturn(FlushMode.AUTO);

    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setSessionFactory(sessionFactory);
    interceptor.setFlushMode(HibernateInterceptor.FLUSH_COMMIT);
    try {/*from   www.  j av a 2 s.  com*/
        interceptor.invoke(invocation);
    } catch (Throwable t) {
        fail("Should not have thrown Throwable: " + t.getMessage());
    } finally {
        TransactionSynchronizationManager.unbindResource(sessionFactory);
    }

    InOrder ordered = inOrder(session);
    ordered.verify(session).setFlushMode(FlushMode.COMMIT);
    ordered.verify(session).setFlushMode(FlushMode.AUTO);
    verify(session, never()).flush();
}