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.eclipse.emf.cdo.server.internal.hibernate.HibernateQueryHandler.java

License:Open Source License

/**
 * Executes hql queries. Gets the session from the {@link HibernateStoreAccessor} creates a hibernate query and sets
 * the parameters taken from the {@link CDOQueryInfo#getParameters()}. Takes into account the
 * {@link CDOQueryInfo#getMaxResults()} and the {@link IHibernateStore#FIRST_RESULT} values for paging.
 *
 * @param info/*  w w  w . j a va2s  .  co m*/
 *          the object containing the query and parameters
 * @param context
 *          the query results are placed in the context
 * @see IQueryHandler#executeQuery(CDOQueryInfo, IQueryContext)
 */
public void executeQuery(CDOQueryInfo info, IQueryContext context) {
    // get a transaction, the hibernateStoreAccessor is placed in a threadlocal
    // so all db access uses the same session.
    final Session session = hibernateStoreAccessor.getHibernateSession();
    try {
        // create the query
        final Query query = session.createQuery(info.getQueryString());
        query.setReadOnly(true);

        // get the parameters with some parameter conversion
        int firstResult = -1;
        boolean cacheResults = true;
        for (String key : info.getParameters().keySet()) {
            if (key.compareToIgnoreCase(IHibernateStore.CACHE_RESULTS) == 0) {
                try {
                    cacheResults = (Boolean) info.getParameters().get(key);
                } catch (ClassCastException e) {
                    throw new IllegalArgumentException("Parameter " + IHibernateStore.CACHE_RESULTS //$NON-NLS-1$
                            + " must be a boolean. errorMessage " + e.getMessage());
                }
            } else if (key.compareToIgnoreCase(IHibernateStore.FIRST_RESULT) == 0) {
                final Object o = info.getParameters().get(key);
                if (o != null) {
                    try {
                        firstResult = (Integer) o;
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException(
                                "Parameter firstResult must be an integer but it is a " + o //$NON-NLS-1$
                                        + " class " + o.getClass().getName()); //$NON-NLS-1$
                    }
                }
            } else {
                // in case the parameter is a CDOID get the object from the db
                final Object param = info.getParameters().get(key);
                if (param instanceof CDOID && HibernateUtil.getInstance().isStoreCreatedID((CDOID) param)) {
                    final CDOID id = (CDOID) param;
                    final String entityName = HibernateUtil.getInstance().getEntityName(id);
                    final Serializable idValue = HibernateUtil.getInstance().getIdValue(id);
                    final CDORevision revision = (CDORevision) session.get(entityName, idValue);
                    query.setEntity(key, revision);
                    if (cacheResults) {
                        addToRevisionCache(revision);
                    }
                } else {
                    query.setParameter(key, param);
                }
            }
        }

        // set the first result
        if (firstResult > -1) {
            query.setFirstResult(firstResult);
        }

        // the max result
        if (info.getMaxResults() != CDOQueryInfo.UNLIMITED_RESULTS) {
            query.setMaxResults(info.getMaxResults());
        }

        final ScrollableResults scroller = query.scroll(ScrollMode.FORWARD_ONLY);

        // and go for the query
        // future extension: support iterate, scroll through a parameter
        int i = 0;
        try {
            while (scroller.next()) {
                Object[] os = scroller.get();
                Object o;
                if (os.length == 1) {
                    o = handleAuditEntries(os[0]);
                } else {
                    o = handleAuditEntries(os);
                }

                final boolean addOneMore = context.addResult(o);
                if (cacheResults && o instanceof CDORevision) {
                    addToRevisionCache((CDORevision) o);
                }
                if (o instanceof InternalCDORevision) {
                    ((InternalCDORevision) o).freeze();
                }

                // clear the session every 1000 results or so
                if (i++ % 1000 == 0) {
                    session.clear();
                }

                if (!addOneMore) {
                    return;
                }
            }
        } finally {
            scroller.close();
        }
    } finally {
        session.close();
    }
}

From source file:org.flowerplatform.web.security.service.PermissionService.java

License:Open Source License

/**
 * Finds {@link PermissionEntity}s that correspond to given {@link PermissionsByResourceFilter} 
 * and returns a list of their corresponding {@link PermissionAdminUIDto}.
 * /*  w  w w .j av  a 2s.co m*/
 */
@SuppressWarnings("unchecked")
public List<PermissionAdminUIDto> findAsAdminUIDtoFilterByResource(PermissionsByResourceFilter resourceFilter) {
    if (resourceFilter == null) {
        return findAllAsAdminUIDto();
    }
    final List<String> patterns = new ArrayList<String>();
    patterns.add(resourceFilter.getResource());
    // add filter by root/dir/* for root/dir
    if (!resourceFilter.getResource().endsWith("/*"))
        patterns.add(resourceFilter.getResource() + (resourceFilter.getResource().endsWith("/") ? "*" : "/*"));
    // add filter by *
    patterns.add("*");
    int fromIndex = 0;
    int index = resourceFilter.getResource().indexOf("/", fromIndex);
    while (index != -1) {
        patterns.add(resourceFilter.getResource().substring(0, index) + "/*");
        fromIndex = index + 1;
        index = resourceFilter.getResource().indexOf("/", fromIndex);
    }

    final List<PermissionAdminUIDto> listDtos = new ArrayList<PermissionAdminUIDto>();
    new DatabaseOperationWrapper(new DatabaseOperation() {

        @Override
        public void run() {
            List<PermissionEntity> permissionEntities;
            Query q = wrapper.createQuery(
                    "SELECT e FROM PermissionEntity e WHERE e.name in :names ORDER by e.type, e.name");
            q.setParameterList("names", patterns);
            q.setReadOnly(true);
            permissionEntities = q.list();

            boolean showAllApplicablePermissions = Boolean.valueOf(CommonPlugin.getInstance()
                    .getFlowerProperties().getProperty(SHOW_ALL_APPLICABLE_PERMISSIONS_PER_FILTERED_RESOURCE));

            for (PermissionEntity permission : permissionEntities) {
                boolean isEditable = false;
                try {
                    SecurityUtils.checkModifyTreePermission(permission);
                    // permission check did not throw a security exception => permission is editable by the current user
                    isEditable = true;
                } catch (SecurityException e) {
                    // do nothing
                }

                // return this permission if it is editable OR if all applicable permissions must be displayed (even if they are not editable by the current user)
                if (isEditable || showAllApplicablePermissions) {
                    PermissionAdminUIDto dto = convertPermissionToPermissionAdminUIDto(permission);
                    dto.setIsEditable(isEditable);
                    listDtos.add(dto);
                }
            }
        }
    });
    return listDtos;
}

From source file:org.gbif.portal.dao.DAOUtils.java

License:Open Source License

/**
 * Process results, scrolling through each record in turn only loading that specific record.
 * /*from  ww w . ja v a 2s .  co m*/
 * @param resultsOutputter
 * @param session
 * @param query
 * @param associationTraverser
 * @param batchSize
 * @throws IOException
 */
public static void scrollResults(final ResultsOutputter resultsOutputter, Session session, Query query,
        AssociationTraverser associationTraverser, int batchSize) throws IOException {
    query.setReadOnly(true);
    query.setFetchSize(batchSize);

    //Using scrollable results to prevent initiation of all model objects
    ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);

    //go to beginning of resultset
    boolean isNotEmpty = sr.first();
    if (!isNotEmpty) {
        //this is necessary due to a bug with ScrollableResults
        //allowing continuous scrolling over an empty resultset. genius.
        return;
    }

    //iterate through the results
    processScrollableResults(resultsOutputter, session, sr, associationTraverser, batchSize);

    //check for a chain
    if (resultsOutputter instanceof ChainableResultsOutputter) {
        ChainableResultsOutputter cro = (ChainableResultsOutputter) resultsOutputter;
        ResultsOutputter nextResultsOutputter = cro.getNextResultsOutputter();
        while (nextResultsOutputter != null && !cro.isChainInOnePass()) {
            //back to the start
            sr.first();
            processScrollableResults(nextResultsOutputter, session, sr, associationTraverser, batchSize);
            if (resultsOutputter instanceof ChainableResultsOutputter) {
                cro = (ChainableResultsOutputter) resultsOutputter;
                if (!cro.isChainInOnePass())
                    nextResultsOutputter = cro.getNextResultsOutputter();
                else
                    nextResultsOutputter = null;
            } else {
                nextResultsOutputter = null;
            }
        }
    }
    if (associationTraverser != null)
        associationTraverser.reset();
    //close the results set
    sr.close();
}

From source file:org.gofleet.openLS.ddbb.dao.postgis.PostGisHBRoutingDAO.java

License:Open Source License

@Transactional(readOnly = true)
public DetermineRouteResponseType routePlan(final DetermineRouteRequestType param) {

    HibernateCallback<DetermineRouteResponseType> action = new HibernateCallback<DetermineRouteResponseType>() {

        @SuppressWarnings("unchecked")
        @Override/*from  w w  w .  j  a  v  a 2 s.c o m*/
        public DetermineRouteResponseType doInHibernate(Session session)
                throws HibernateException, SQLException {
            Query consulta = session.getNamedQuery("tsp");

            WayPointListType wayPointList = param.getRoutePlan().getWayPointList();

            List<Geometry> stops = new LinkedList<Geometry>();
            for (WayPointType wayPoint : wayPointList.getViaPoint()) {
                stops.add(GeoUtil.getPoint(wayPoint, null));
            }
            stops.add(GeoUtil.getPoint(wayPointList.getEndPoint(), null));

            consulta.setString("tablename", TABLE_NAME);
            consulta.setParameterList("stoptable", stops, GeometryUserType.TYPE);
            consulta.setString("gid", ROUTING_ID);
            consulta.setParameter("start", GeoUtil.getPoint(wayPointList.getStartPoint(), null),
                    GeometryUserType.TYPE);

            consulta.setReadOnly(true);
            LOG.debug(consulta);

            return getRouteResponse(consulta.list());

        }

    };
    return hibernateTemplate.executeWithNativeSession(action);
}

From source file:org.gofleet.openLS.ddbb.dao.RoutingDAO.java

License:Open Source License

@Transactional(readOnly = true)
public DetermineRouteResponseType routePlan(final DetermineRouteRequestType param) {

    HibernateCallback<DetermineRouteResponseType> action = new HibernateCallback<DetermineRouteResponseType>() {

        @SuppressWarnings("unchecked")
        public DetermineRouteResponseType doInHibernate(Session session)
                throws HibernateException, SQLException {
            Query consulta = session.getNamedQuery("tsp");

            WayPointListType wayPointList = param.getRoutePlan().getWayPointList();

            List<Geometry> stops = new LinkedList<Geometry>();
            for (WayPointType wayPoint : wayPointList.getViaPoint()) {
                stops.add(GeoUtil.getPoint(wayPoint));
            }/*  w w  w .  j  av  a  2s. c o  m*/
            stops.add(GeoUtil.getPoint(wayPointList.getEndPoint()));

            consulta.setString("tablename", TABLE_ROUTING);
            consulta.setParameterList("stoptable", stops, GeometryUserType.TYPE);
            consulta.setString("gid", GID_ROUTING);
            consulta.setParameter("start", GeoUtil.getPoint(wayPointList.getStartPoint()),
                    GeometryUserType.TYPE);

            consulta.setReadOnly(true);
            LOG.debug(consulta);

            return getRouteResponse(consulta.list());

        }

    };
    return hibernateTemplate.executeWithNativeSession(action);
}

From source file:org.grails.orm.hibernate.GrailsHibernateTemplate.java

License:Apache License

/**
 * Prepare the given Query object, applying cache settings and/or a
 * transaction timeout./* w w w.j av a 2 s .  co  m*/
 *
 * @param query the Query object to prepare
 */
protected void prepareQuery(Query query) {
    if (cacheQueries) {
        query.setCacheable(true);
    }
    if (shouldPassReadOnlyToHibernate()) {
        query.setReadOnly(true);
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        query.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}

From source file:org.headsupdev.agile.storage.HibernateStorage.java

License:Open Source License

public List<Event> getEvents(Date start) {
    Session session = getHibernateSession();
    Query q = session.createQuery("from StoredEvent e where time >= :start order by time desc");
    q.setDate("start", start);

    q.setReadOnly(true);
    return (List<Event>) q.list();
}

From source file:org.headsupdev.agile.storage.HibernateStorage.java

License:Open Source License

public List<Event> getEvents(Date start, Date end) {
    Session session = getHibernateSession();
    Query q = session.createQuery("from StoredEvent e where time >= :start and time < :end order by time desc");
    q.setDate("start", start);
    q.setDate("end", end);

    q.setReadOnly(true);
    return (List<Event>) q.list();
}

From source file:org.headsupdev.agile.storage.HibernateStorage.java

License:Open Source License

public List<Event> getEvents(Application app, Date start, Date end) {
    Session session = getHibernateSession();
    Query q = session.createQuery(
            "from StoredEvent e where applicationId = :appId and time >= :start and time < :end order by time desc");
    q.setString("appId", app.getApplicationId());
    q.setTimestamp("start", start);
    q.setTimestamp("end", end);

    q.setReadOnly(true);
    return (List<Event>) q.list();
}

From source file:org.headsupdev.agile.storage.HibernateStorage.java

License:Open Source License

private List<Event> doGetEventsForProject(Project project, Application app, Date start, Date end,
        boolean tree) {
    String query = "from StoredEvent e where project.id = :pid";
    if (tree) {/*from   w w  w  .  j a v a 2  s.  co m*/
        query = "from StoredEvent e where project.id in (:pids)";
    }

    if (app != null) {
        query += " and applicationId = :appId";
    }

    if (start != null) {
        query += " and time >= :start and time < :end";
    }
    query += " order by time desc";

    Session session = getHibernateSession();
    Transaction tx = session.beginTransaction();
    Query q = session.createQuery(query);

    if (tree) {
        project = (Project) session.merge(project);
        List<String> projects = new LinkedList<String>();
        doListProjectIds(project, projects);
        q.setParameterList("pids", projects);
    } else {
        q.setString("pid", project.getId());
    }

    if (app != null) {
        q.setString("appId", app.getApplicationId());
    }

    if (start != null) {
        q.setTimestamp("start", start);
        q.setTimestamp("end", end);
    }

    q.setReadOnly(true);
    List<Event> list = q.list();
    tx.commit();

    return list;
}