Example usage for org.hibernate Query setReadOnly

List of usage examples for org.hibernate Query setReadOnly

Introduction

In this page you can find the example usage for org.hibernate Query setReadOnly.

Prototype

Query<R> setReadOnly(boolean readOnly);

Source Link

Document

Set the read-only/modifiable mode for entities and proxies loaded by this Query.

Usage

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 a v a 2s  .  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 ww .java 2s.  com
    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.rhq.server.metrics.migrator.datasources.ScrollableDataSource.java

License:Open Source License

@Override
public void initialize() {
    if (session != null || results != null) {
        close();//from   ww w.j  ava2  s  .c  om
    }

    session = ((Session) entityManager.getDelegate()).getSessionFactory().openStatelessSession();

    this.prepareSQLSession();

    if (log.isDebugEnabled()) {
        if (maxResults >= 0) {
            log.debug("Preparing the query with " + maxResults + " results.");
        } else {
            log.debug("Preparing the query with all the results.");
        }
    }

    Query query = session.createSQLQuery(selectNativeQuery);
    if (maxResults >= 0) {
        query.setMaxResults(maxResults);
    }
    query.setFetchSize(30000);
    query.setReadOnly(true);
    query.setTimeout(TIMEOUT);
    results = query.scroll(ScrollMode.FORWARD_ONLY);

    lastMigratedItemIndex = -1;

    if (log.isDebugEnabled()) {
        if (maxResults >= 0) {
            log.debug("Query prepared with " + maxResults + " results.");
        } else {
            log.debug("Query prepared with all the results.");
        }
    }
}

From source file:org.rhq.server.metrics.migrator.datasources.ScrollableDataSource.java

License:Open Source License

private void prepareSQLSession() {
    if (DatabaseType.Postgres.equals(this.databaseType)) {
        log.debug("Preparing SQL connection with timeout: " + DataMigrator.SQL_TIMEOUT);

        Query query = session.createSQLQuery("SET LOCAL statement_timeout = " + DataMigrator.SQL_TIMEOUT);
        query.setReadOnly(true);
        query.executeUpdate();//from   w  w  w .ja  va2  s.co m
    }
}

From source file:org.rhq.server.metrics.migrator.workers.AbstractMigrationWorker.java

License:Open Source License

protected void prepareSQLSession(StatelessSession session, DataMigratorConfiguration config) {
    if (DatabaseType.Postgres.equals(config.getDatabaseType())) {
        log.debug("Preparing SQL connection with timeout: " + DataMigrator.SQL_TIMEOUT);

        org.hibernate.Query query = session
                .createSQLQuery("SET LOCAL statement_timeout = " + DataMigrator.SQL_TIMEOUT);
        query.setReadOnly(true);
        query.executeUpdate();/*from www.  ja v  a2s.  c  om*/
    }
}

From source file:org.rhq.server.metrics.migrator.workers.AggregateDataMigrator.java

License:Open Source License

private long getRowCount(String countQuery) {
    StatelessSession session = getSQLSession(config);

    org.hibernate.Query query = session.createSQLQuery(countQuery);
    query.setReadOnly(true);
    query.setTimeout(DataMigrator.SQL_TIMEOUT);
    long count = Long.parseLong(query.uniqueResult().toString());

    closeSQLSession(session);/*from  w w  w .  ja  v  a  2  s  .c o m*/

    return count;
}

From source file:org.rhq.server.metrics.migrator.workers.RawDataMigrator.java

License:Open Source License

private long getRowCount(String countQuery) {
    StatelessSession session = getSQLSession(config);

    org.hibernate.Query query = session.createSQLQuery(countQuery);
    query.setReadOnly(true);
    query.setTimeout(DataMigrator.SQL_TIMEOUT);

    long count = Long.parseLong(query.uniqueResult().toString());

    closeSQLSession(session);/*from w  w  w.java2 s. co  m*/

    return count;
}

From source file:org.squashtest.tm.service.internal.repository.hibernate.TestCaseDaoImpl.java

License:Open Source License

private List<NamedReferencePair> findTestCaseCallsDetails(final Collection<Long> testCaseIds,
        String mainQuery) {/*from  w w w. ja  v a  2s  .co m*/
    if (testCaseIds.isEmpty()) {
        return Collections.emptyList();
    }

    // the easy part : fetch the informations for those who are called
    SetQueryParametersCallback queryCallback = new SetQueryParametersCallback() {
        @Override
        public void setQueryParameters(Query query) {
            query.setParameterList(TEST_CASE_IDS_PARAM_NAME, testCaseIds, new LongType());
            query.setReadOnly(true);
        }
    };

    return executeListNamedQuery(mainQuery, queryCallback);

}

From source file:org.webcurator.domain.TargetInstanceDAOImpl.java

License:Apache License

/**
* Return the DTO for the specified Target Instance.
* @param aOid the oid of the target instance DTO to return
* @return the target instance DTO//from  ww  w  .  j a va 2 s.  co m
*/
public TargetInstanceDTO getTargetInstanceDTO(final Long aOid) {
    if (log.isDebugEnabled()) {
        log.debug("Get DTO for target instance: " + aOid);
    }
    return (TargetInstanceDTO) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {

            StringBuffer q = new StringBuffer();
            q.append(
                    "select new org.webcurator.domain.model.dto.TargetInstanceDTO(ti.oid, ti.scheduledTime, ti.priority, ti.state, ti.owner.oid) ");
            q.append("from TargetInstance ti where ti.oid = :oid ");

            Query query = session.createQuery(q.toString());

            query.setLong("oid", aOid);
            query.setReadOnly(true);

            return query.uniqueResult();
        }
    });
}

From source file:sernet.gs.ui.rcp.main.service.crudcommands.FastLoadCnAElementsByIds.java

License:Open Source License

public void execute() {
    IBaseDao<Entity, Serializable> dao = getDaoFactory().getDAO(Entity.class);
    foundItems = new ArrayList<Entity>();

    List list = dao.findByCallback(new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createQuery("from Entity e " + "where e.dbId in (:dbids)")
                    .setParameterList("dbids", dbIDs);
            query.setReadOnly(true);
            List result = query.list();
            return result;
        }//www.  j  a v a  2s .co  m
    });

    for (Object object : list) {
        Entity elmt = (Entity) object;
        foundItems.add(elmt);
    }
}