Example usage for org.hibernate CacheMode IGNORE

List of usage examples for org.hibernate CacheMode IGNORE

Introduction

In this page you can find the example usage for org.hibernate CacheMode IGNORE.

Prototype

CacheMode IGNORE

To view the source code for org.hibernate CacheMode IGNORE.

Click Source Link

Document

The session will never interact with the cache, except to invalidate cache items when updates occur.

Usage

From source file:org.openspaces.persistency.hibernate.iterator.DefaultScrollableDataIterator.java

License:Open Source License

protected ScrollableResults createCursor() {
    session = sessionFactory.openSession();
    session.setFlushMode(FlushMode.MANUAL);
    transaction = session.beginTransaction();
    if (entityName != null) {
        Criteria criteria = session.createCriteria(entityName);
        criteria.setCacheable(false);//from   w  w  w .ja  v a2  s  .c  om
        criteria.setFlushMode(FlushMode.MANUAL);
        criteria.setFetchSize(fetchSize);
        if (perfromOrderById) {
            ClassMetadata metadata = sessionFactory.getClassMetadata(entityName);
            String idPropName = metadata.getIdentifierPropertyName();
            if (idPropName != null) {
                criteria.addOrder(Order.asc(idPropName));
            }
        }
        if (from >= 0) {
            if (from > 0)
                criteria.setFirstResult(from);
            criteria.setMaxResults(size);
        }
        return criteria.scroll(ScrollMode.FORWARD_ONLY);
    } else if (sqlQuery != null) {
        Query query = HibernateIteratorUtils.createQueryFromSQLQuery(sqlQuery, session);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else if (hQuery != null) {
        Query query = session.createQuery(hQuery);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        query.setCacheMode(CacheMode.IGNORE);
        query.setCacheable(false);
        query.setReadOnly(true);
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else {
        throw new IllegalStateException("No SQLQuery, entity, or Hibernate Query provided");
    }
}

From source file:org.openspaces.persistency.hibernate.iterator.HibernateIteratorUtils.java

License:Open Source License

public static Query createQueryFromSQLQuery(SQLQuery<?> sqlQuery, Session session) {
    String select = sqlQuery.getFromQuery();
    Query query = session.createQuery(select);
    Object[] preparedValues = sqlQuery.getParameters();
    if (preparedValues != null) {
        for (int i = 0; i < preparedValues.length; i++) {
            query.setParameter(i, preparedValues[i]);
        }/*from  w w  w.  jav a 2  s.  c  om*/
    }
    query.setCacheMode(CacheMode.IGNORE);
    query.setCacheable(false);
    query.setReadOnly(true);
    return query;
}

From source file:org.opentaps.search.HibernateSearchRepository.java

License:Open Source License

/** {@inheritDoc} */
public void searchInEntities(Set<Class<?>> entityClasses, String queryString, int pageStart, int pageSize)
        throws RepositoryException {

    Debug.logInfo("searchInEntities: [" + entityClasses + "] query [" + queryString + "] page start ["
            + pageStart + "] pageSize [" + pageSize + "]", MODULE);
    Session session = null;/*w  w w.  j av a 2  s . c  o  m*/
    FullTextSession fullTextSession = null;
    Transaction tx = null;
    try {
        session = getInfrastructure().getSession();
        fullTextSession = Search.getFullTextSession(session.getHibernateSession());
        fullTextSession.setCacheMode(CacheMode.IGNORE);
        tx = fullTextSession.beginTransaction();
        // create a native Lucene query
        QueryParser parser = new QueryParser("_hibernate_class", new KeywordAnalyzer());
        Query luceneQuery = parser.parse(queryString);
        // create the full text query
        FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery,
                entityClasses.toArray(new Class[entityClasses.size()]));
        fullTextQuery.setProjection(new String[] { FullTextQuery.OBJECT_CLASS, FullTextQuery.ID });
        // perform the query
        List<Object[]> queryResults = fullTextQuery.list();
        resultSize = fullTextQuery.getResultSize();
        Debug.logInfo("searchInEntities: found " + resultSize + " total results.", MODULE);
        Debug.logInfo("searchInEntities: list contains " + queryResults.size() + " results.", MODULE);

        // a Verbose debug of all results (in current pagination range)
        // and map the query results into SearchResult objects
        results = new ArrayList<SearchResult>();
        Debug.logInfo("------- end of results (total " + resultSize + ") -------", MODULE);
        int i = pageStart + 1;
        for (Object[] o : queryResults) {
            StringBuilder sb = new StringBuilder(" ").append(i).append(" --> ");
            for (Object detail : o) {
                sb.append(detail).append(" ");
            }
            Debug.logInfo(sb.toString(), MODULE);
            i++;

            results.add(new SearchResult((Class<?>) o[0], o[1]));

        }
        Debug.logInfo("------- end of results (total " + resultSize + ") -------", MODULE);

        tx.commit();
    } catch (ParseException e) {
        Debug.logError(e, "Error parsing lucene query [" + queryString + "].", MODULE);
        // rollback the transaction
        if (tx != null) {
            try {
                tx.rollback();
            } catch (Exception e2) {
                Debug.logWarning(e2, "Could not rollback the hibernate transaction on error.", MODULE);
            }
        }
        throw new RepositoryException(e);
    } catch (InfrastructureException e) {
        Debug.logError(e, "Error getting the hibernate session.", MODULE);
        // rollback the transaction
        if (tx != null) {
            try {
                tx.rollback();
            } catch (Exception e2) {
                Debug.logWarning(e2, "Could not rollback the hibernate transaction on error.", MODULE);
            }
        }
        throw new RepositoryException(e);
    } finally {
        // close the sessions
        try {
            if (fullTextSession != null) {
                fullTextSession.close();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "Could not close the FullTextSession.", MODULE);
        }

        try {
            if (session != null && session.isOpen()) {
                Debug.logWarning("Session still open, closing.", MODULE);
                session.close();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "Could not close the Session.", MODULE);
        }
    }
}

From source file:org.opentaps.search.IndexingService.java

License:Open Source License

/**
 * Creates the hibernate search index for a given Entity class.
 * @param fullTextSession a <code>FullTextSession</code> value
 * @param entityClass a <code>Class</code> value
 *///from ww  w.  j av a  2s .c om
@SuppressWarnings("unchecked")
private void createIndexForEntity(FullTextSession fullTextSession, Class entityClass) {
    Criteria query = fullTextSession.createCriteria(entityClass)
            //load necessary associations
            .setFetchMode("distributor", FetchMode.JOIN)
            //distinct them (due to collection load)
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            //set flush mode, ensure it will write to disk on commit the transaction
            .setFlushMode(FlushMode.COMMIT)
            //minimize cache interaction
            .setCacheMode(CacheMode.IGNORE).setFetchSize(Session.FETCH_SIZE);
    //scroll in forward only
    ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
    int batch = 0;
    while (scroll.next()) {
        batch++;
        fullTextSession.index(scroll.get(0));
        if (batch % Session.FETCH_SIZE == 0) {
            // batch flush index into session per FETCH_SIZE
            fullTextSession.flushToIndexes();
            fullTextSession.clear();
        }
    }
    // flush last changes
    fullTextSession.flushToIndexes();
    fullTextSession.getSearchFactory().optimize(entityClass);
}

From source file:org.opentaps.search.IndexingService.java

License:Open Source License

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public void createIndexForGenericEntity() throws ServiceException {

    if (value == null) {
        Debug.logError("Cannot create index for null value.", MODULE);
        return;//w ww  .j a v  a 2 s.c  om
    }

    Session session = null;
    FullTextSession fullTextSession = null;
    Transaction tx = null;

    try {
        // open a session
        session = getInfrastructure().getSession();
        // create FullTextSession by original hibernate session.
        fullTextSession = Search.getFullTextSession(session.getHibernateSession());
        fullTextSession.setFlushMode(FlushMode.COMMIT);
        fullTextSession.setCacheMode(CacheMode.IGNORE);

        tx = fullTextSession.beginTransaction();

        String entityName = value.getEntityName();
        ModelEntity modelEntity = value.getModelEntity();
        List<String> pkFieldNames = modelEntity.getPkFieldNames();

        Class cls = Class.forName("org.opentaps.base.entities." + entityName);
        Serializable id = null;

        if (pkFieldNames.size() > 1) {
            // multi fields pk
            Class pkCls = Class.forName("org.opentaps.base.entities." + entityName + "Pk");
            id = (Serializable) pkCls.newInstance();
            for (String pkFieldName : pkFieldNames) {
                HibernateUtil.setFieldValue(id, pkFieldName, value.get(pkFieldName));
            }
        } else if (pkFieldNames.size() == 1) {
            // simple field pk
            id = (Serializable) value.get(pkFieldNames.get(0));
        }

        Debug.logInfo("createIndexForGenericEntity: got id [" + id + "] for entity: " + entityName, MODULE);
        if (id != null) {
            Entity entity = (Entity) fullTextSession.get(cls, id);
            if (entity != null) {
                fullTextSession.index(entity);
            } else {
                fullTextSession.purge(cls, id);
            }
        }

        // flush last changes
        fullTextSession.flushToIndexes();
        fullTextSession.clear();
        tx.commit();
        Debug.logInfo("createIndexForGenericEntity: index committed", MODULE);
        if (session.isDirty()) {
            Debug.logWarning("Session still dirty ??", MODULE);
        }

    } catch (Exception e) {
        Debug.logError(e, MODULE);
        // rollback the transaction
        if (tx != null) {
            try {
                tx.rollback();
            } catch (Exception e2) {
                Debug.logWarning(e2, "Could not rollback the hibernate transaction on error.", MODULE);
            }
        }
        throw new ServiceException(e);
    } finally {
        // close the sessions
        try {
            if (fullTextSession != null) {
                fullTextSession.close();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "Could not close the FullTextSession.", MODULE);
        }

        try {
            if (session != null && session.isOpen()) {
                Debug.logWarning("Session still open, closing.", MODULE);
                session.close();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "Could not close the Session.", MODULE);
        }
    }
}

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

License:Open Source License

private synchronized Session getSession() {
    Session session = null;//from ww  w . j  a  va  2 s.c o  m
    if (local != null) {
        session = local.get();
        if (session == null) {
            session = HibernateUtil.getSessionFactory().openSession();
            session.setCacheMode(CacheMode.IGNORE);
        }
        local.set(session);
    } else {
        session = HibernateUtil.getSessionFactory().openSession();
        session.setCacheMode(CacheMode.IGNORE);
    }
    return session;
}

From source file:org.ow2.bonita.util.IndexTool.java

License:Open Source License

private static void populateIndexes(SessionFactoryImplementor sessionFactory) throws InterruptedException {
    FullTextSession fullTextSession = null;
    try {//w ww. j a va2  s .c o m
        Session session = sessionFactory.openSession();
        fullTextSession = Search.getFullTextSession(session);
        Transaction tx = fullTextSession.beginTransaction();
        MassIndexer indexer = fullTextSession.createIndexer();
        indexer.cacheMode(CacheMode.IGNORE);
        indexer.startAndWait();
        fullTextSession.createIndexer();
        tx.commit();
    } finally {
        if (fullTextSession != null) {
            fullTextSession.close();
        }
    }
}

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  ww  . j  av  a 2 s .  c om
    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;//from  w  w w. ja  v a 2 s  .co  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./*from ww w  .j a va 2s  .  com*/
 * 
 * @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;
}