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:sernet.gs.ui.rcp.main.service.taskcommands.FindLinkedPersons.java

License:Open Source License

@SuppressWarnings("unchecked")
public void execute() {
    // preload Entities:
    final Set<Integer> dbIds = new HashSet<Integer>();
    for (UnresolvedItem item : unresolvedItems) {
        dbIds.addAll(getEntityIDs(item.getUmsetzungDurchLinks()));
        dbIds.addAll(getEntityIDs(item.getRevisionDurchLinks()));
    }/* w  ww .j a va  2s . c om*/

    if (dbIds.size() == 0) {
        return;
    }
    IBaseDao<Person, Serializable> dao = getDaoFactory().getDAO(Person.class);
    List<Entity> personenEntities = 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;
        }
    });
    Map<Integer, Entity> personenMap = new HashMap<Integer, Entity>();
    for (Entity entity : personenEntities) {
        personenMap.put(entity.getDbId(), entity);
    }

    // set auditors:
    for (UnresolvedItem unresolvedItem : unresolvedItems) {
        Set<Integer> entityIDs = getEntityIDs(unresolvedItem.getRevisionDurchLinks());
        String names = getNames(personenMap, entityIDs);
        if (names.length() > 0) {
            unresolvedItem.getItem().setRevisionDurch(names);
        }
    }

    // set responsible persons:
    for (Iterator<UnresolvedItem> iterator = unresolvedItems.iterator(); iterator.hasNext();) {
        UnresolvedItem unresolvedItem = iterator.next();
        Set<Integer> entityIDs = getEntityIDs(unresolvedItem.getUmsetzungDurchLinks());
        String names = getNames(personenMap, entityIDs);
        if (names.length() > 0) {
            unresolvedItem.getItem().setUmsetzungDurch(names);
            resolvedItems.add(unresolvedItem.getItem());
            // do not try to find person by role later:
            iterator.remove();
        }

    }
}

From source file:ubic.gemma.persistence.service.common.auditAndSecurity.AuditEventDaoImpl.java

License:Apache License

private Map<Auditable, AuditEvent> getLastEvent(final Collection<? extends Auditable> auditables,
        Class<? extends AuditEventType> type) {

    Map<Auditable, AuditEvent> result = new HashMap<>();
    if (auditables.size() == 0)
        return result;

    final Map<AuditTrail, Auditable> atMap = this.getAuditTrailMap(auditables);

    List<String> classes = this.getClassHierarchy(type);

    //language=HQL
    final String queryString = "select trail, ae from AuditTrailImpl trail "
            + "inner join trail.events ae inner join ae.eventType et inner join fetch ae.performer where trail in (:trails) "
            + "and et.class in (:classes) order by ae.date desc, ae.id desc ";

    StopWatch timer = new StopWatch();
    timer.start();// w w  w  . j av  a  2  s. c  o  m

    Collection<AuditTrail> batch = new ArrayList<>();
    int batchSize = 100;

    for (AuditTrail at : atMap.keySet()) {
        batch.add(at);

        if (batch.size() == batchSize) {
            org.hibernate.Query queryObject = this.getSessionFactory().getCurrentSession()
                    .createQuery(queryString);
            queryObject.setParameterList("trails", batch);
            queryObject.setParameterList("classes", classes);
            queryObject.setReadOnly(true);

            List<?> qr = queryObject.list();
            if (qr == null || qr.isEmpty()) {
                batch.clear();
                continue;
            }

            this.putAllQrs(result, qr, atMap);
            batch.clear();
        }
    }

    if (!batch.isEmpty()) {
        org.hibernate.Query queryObject = this.getSessionFactory().getCurrentSession().createQuery(queryString);
        queryObject.setParameterList("trails", batch); // if too many will fail.
        queryObject.setParameterList("classes", classes);
        queryObject.setReadOnly(true);

        List<?> qr = queryObject.list();
        if (qr == null || qr.isEmpty())
            return result;

        this.putAllQrs(result, qr, atMap);
    }

    timer.stop();
    if (timer.getTime() > 500) {
        AbstractDao.log.info("Last event of type " + type.getSimpleName() + " retrieved for "
                + auditables.size() + " items in " + timer.getTime() + "ms");
    }

    return result;
}

From source file:ubic.gemma.persistence.service.common.auditAndSecurity.AuditEventDaoImpl.java

License:Apache License

private AuditEvent getLastEvent(final AuditTrail auditTrail, Class<? extends AuditEventType> type) {

    /*/*from   w  w  w  .j  a  v a  2s.  c  om*/
     * For the = operator to work in hibernate the class or class name can't be passed in as a parameter :type -
     * also queryObject.setParameter("type", type.getClass()); doesn't work. Although technically this is now
     * vulnerable to an sql injection attack, it seems moot as an attacker would have to have access to the JVM to
     * inject a malformed AuditEventType class name and if they had access to the JVM then sql injection is the
     * least of our worries. The real annoyance here is dealing with subclasses of event types.
     */

    List<String> classes = this.getClassHierarchy(type);

    if (classes.size() == 0) {
        return null;
    }

    //language=HQL
    final String queryString = "select event from AuditTrailImpl trail "
            + "inner join trail.events event inner join event.eventType et inner join fetch event.performer "
            + "fetch all properties where trail = :trail and et.class in (:classes) "
            + "order by event.date,event.id desc ";

    org.hibernate.Query queryObject = this.getSessionFactory().getCurrentSession().createQuery(queryString);
    queryObject.setCacheable(true);
    queryObject.setReadOnly(true);
    queryObject.setParameter("trail", auditTrail);
    queryObject.setParameterList("classes", classes);
    queryObject.setMaxResults(1);

    //noinspection unchecked
    Collection<AuditEvent> results = queryObject.list();

    if (results == null || results.isEmpty())
        return null;

    AuditEvent result = results.iterator().next();
    Hibernate.initialize(result.getPerformer()); // Hit performer to make hibernate initialize it.
    return result;

}

From source file:ubic.gemma.persistence.service.expression.arrayDesign.ArrayDesignDaoImpl.java

License:Apache License

@Override
public Map<Taxon, Long> getPerTaxonCount() {
    Map<Taxon, Long> result = new HashMap<>();

    final String csString = "select t, count(ad) from ArrayDesign ad inner join ad.primaryTaxon t group by t ";
    org.hibernate.Query csQueryObject = this.getSessionFactory().getCurrentSession().createQuery(csString);
    csQueryObject.setReadOnly(true);
    csQueryObject.setCacheable(true);//from  w ww . jav  a 2  s  .  c  o m

    List csList = csQueryObject.list();

    Taxon t;
    for (Object object : csList) {
        Object[] oa = (Object[]) object;
        t = (Taxon) oa[0];
        Long count = (Long) oa[1];

        result.put(t, count);
    }

    return result;

}

From source file:ubic.gemma.persistence.service.expression.bioAssayData.DesignElementDataVectorDaoImpl.java

License:Apache License

/**
 * @param  ee      ee//from w  ww .  j  av  a2s .  co  m
 * @param  cs2gene Map of probes to genes.
 * @return         map of vectors to gene ids.
 */
Map<T, Collection<Long>> getVectorsForProbesInExperiments(Long ee, Map<Long, Collection<Long>> cs2gene) {

    // Do not do in clause for experiments, as it can't use the indices
    //language=HQL
    String queryString = "select dedv, dedv.designElement.id from ProcessedExpressionDataVector dedv fetch all properties"
            + " where dedv.designElement.id in ( :cs ) and dedv.expressionExperiment.id = :eeId ";

    Session session = this.getSessionFactory().getCurrentSession();
    org.hibernate.Query queryObject = session.createQuery(queryString);
    queryObject.setReadOnly(true);
    queryObject.setFlushMode(FlushMode.MANUAL);

    Map<T, Collection<Long>> dedv2genes = new HashMap<>();
    StopWatch timer = new StopWatch();
    timer.start();

    queryObject.setLong("eeId", ee);

    int batchSize = 100;
    for (Collection<Long> batch : new BatchIterator<>(cs2gene.keySet(), batchSize)) {
        this.getVectorsBatch(cs2gene, queryObject, dedv2genes, batch);
    }

    if (timer.getTime() > Math.max(200, 20 * dedv2genes.size())) {
        AbstractDao.log.info("Fetched " + dedv2genes.size() + " vectors for " + cs2gene.size() + " probes in "
                + timer.getTime() + "ms\n" + "Vector query was: " + queryString);

    }
    return dedv2genes;
}

From source file:ubic.gemma.persistence.service.expression.bioAssayData.DesignElementDataVectorDaoImpl.java

License:Apache License

Map<T, Collection<Long>> getVectorsForProbesInExperiments(Map<Long, Collection<Long>> cs2gene) {

    //language=HQL
    String queryString = "select dedv, dedv.designElement.id from ProcessedExpressionDataVector dedv fetch all properties"
            + " where dedv.designElement.id in ( :cs ) ";

    Session session = this.getSessionFactory().getCurrentSession();
    org.hibernate.Query queryObject = session.createQuery(queryString);
    queryObject.setReadOnly(true);
    queryObject.setFlushMode(FlushMode.MANUAL);

    Map<T, Collection<Long>> dedv2genes = new HashMap<>();
    StopWatch timer = new StopWatch();
    timer.start();//w  ww.  java 2  s.  com

    int batchSize = 100;
    for (Collection<Long> batch : new BatchIterator<>(cs2gene.keySet(), batchSize)) {
        this.getVectorsBatch(cs2gene, queryObject, dedv2genes, batch);
    }

    if (timer.getTime() > Math.max(200, 20 * dedv2genes.size())) {
        AbstractDao.log.info("Fetched " + dedv2genes.size() + " vectors for " + cs2gene.size() + " probes in "
                + timer.getTime() + "ms\n" + "Vector query was: " + queryString);

    }
    return dedv2genes;
}

From source file:ubic.gemma.persistence.service.expression.bioAssayData.DesignElementDataVectorDaoImpl.java

License:Apache License

private void getVectorsBatch(Map<Long, Collection<Long>> cs2gene, org.hibernate.Query queryObject,
        Map<T, Collection<Long>> dedv2genes, Collection<Long> batch) {
    queryObject.setParameterList("cs", batch);
    queryObject.setFlushMode(FlushMode.MANUAL);
    queryObject.setReadOnly(true);
    ScrollableResults results = queryObject.scroll(ScrollMode.FORWARD_ONLY);

    while (results.next()) {
        @SuppressWarnings("unchecked")
        T dedv = (T) results.get(0);//  www.  j a  v a  2  s  .  com
        Long cs = (Long) results.get(1);
        Collection<Long> associatedGenes = cs2gene.get(cs);
        if (!dedv2genes.containsKey(dedv)) {
            dedv2genes.put(dedv, associatedGenes);
        } else {
            Collection<Long> mappedGenes = dedv2genes.get(dedv);
            mappedGenes.addAll(associatedGenes);
        }
    }

    results.close();
}

From source file:ubic.gemma.persistence.service.expression.bioAssayData.ProcessedExpressionDataVectorDaoImpl.java

License:Apache License

/**
 * @param limit if non-null and positive, you will get a random set of vectors for the experiment
 * @param ee    ee/*from   w  w  w  . j  ava2s.c  o  m*/
 * @return processed data vectors
 */
private Collection<ProcessedExpressionDataVector> getProcessedVectors(ExpressionExperiment ee, Integer limit) {

    if (limit == null || limit < 0) {
        return this.getProcessedVectors(ee);
    }

    StopWatch timer = new StopWatch();
    timer.start();
    List<ProcessedExpressionDataVector> result;

    Integer availableVectorCount = ee.getNumberOfDataVectors();
    if (availableVectorCount == null || availableVectorCount == 0) {
        AbstractDao.log.info("Experiment does not have vector count populated.");
        // cannot fix this here, because we're read-only.
    }

    Query q = this.getSessionFactory().getCurrentSession()
            .createQuery(" from ProcessedExpressionDataVector dedv where dedv.expressionExperiment.id = :ee");
    q.setParameter("ee", ee.getId(), LongType.INSTANCE);
    q.setMaxResults(limit);
    if (availableVectorCount != null && availableVectorCount > limit) {
        q.setFirstResult(new Random().nextInt(availableVectorCount - limit));
    }

    // we should already be read-only, so this is probably pointless.
    q.setReadOnly(true);

    // and so this probably doesn't do anything useful.
    q.setFlushMode(FlushMode.MANUAL);

    //noinspection unchecked
    result = q.list();
    if (timer.getTime() > 1000)
        AbstractDao.log
                .info("Fetch " + limit + " vectors from " + ee.getShortName() + ": " + timer.getTime() + "ms");

    if (result.isEmpty()) {
        AbstractDao.log.warn("Experiment does not have any processed data vectors");
        return result;
    }

    this.thaw(result); // needed?
    return result;
}

From source file:ubic.gemma.persistence.util.CommonQueries.java

License:Apache License

/**
 * @param ees     collection of expression experiments.
 * @param session session/*from  ww w.  java 2s . c  o  m*/
 * @return map of array designs to the experiments they were used in.
 */
public static Map<ArrayDesign, Collection<Long>> getArrayDesignsUsed(Collection<Long> ees, Session session) {
    Map<ArrayDesign, Collection<Long>> eeAdMap = new HashMap<>();

    // Safety 1st....
    if (ees == null || ees.isEmpty())
        return eeAdMap;

    final String eeAdQuery = "select distinct ee.id,ad from ExpressionExperiment as ee inner join "
            + "ee.bioAssays b inner join b.arrayDesignUsed ad fetch all properties where ee.id in (:ees)";

    org.hibernate.Query queryObject = session.createQuery(eeAdQuery);
    queryObject.setParameterList("ees", ees);
    queryObject.setReadOnly(true);
    queryObject.setFlushMode(FlushMode.MANUAL);

    List<?> qr = queryObject.list();
    for (Object o : qr) {
        Object[] ar = (Object[]) o;
        Long ee = (Long) ar[0];
        ArrayDesign ad = (ArrayDesign) ar[1];
        if (!eeAdMap.containsKey(ad)) {
            eeAdMap.put(ad, new HashSet<Long>());
        }
        eeAdMap.get(ad).add(ee);
    }

    return eeAdMap;
}

From source file:ubic.gemma.persistence.util.CommonQueries.java

License:Apache License

/**
 * @param ees     experiments//from  ww  w.java2 s.  c  om
 * @param session session
 * @return map of experiment to collection of array design ids. If any of the ids given are for subsets, then the
 * key in the return value will be for the subset, not the source experiment (so it is consistent with the
 * input)
 */
public static Map<Long, Collection<Long>> getArrayDesignsUsedEEMap(Collection<Long> ees, Session session) {
    Map<Long, Collection<Long>> ee2ads = new HashMap<>();

    if (ees == null || ees.isEmpty())
        return ee2ads;

    final String eeAdQuery = "select distinct ee.id,ad.id from ExpressionExperiment as ee inner join "
            + "ee.bioAssays b inner join b.arrayDesignUsed ad where ee.id in (:ees)";

    org.hibernate.Query queryObject = session.createQuery(eeAdQuery);
    queryObject.setParameterList("ees", ees);
    queryObject.setReadOnly(true);
    queryObject.setFlushMode(FlushMode.MANUAL);

    List<?> qr = queryObject.list();
    ee2ads = CommonQueries.addAllAds(ee2ads, qr);

    if (ee2ads.size() < ees.size()) {
        // ids might be invalid, but also might be subsets. Note that the output key is for the subset, not the
        // source.
        String subsetQuery = "select distinct ees.id,ad.id from ExpressionExperimentSubSet as ees join ees.sourceExperiment ee "
                + " join ee.bioAssays b join b.arrayDesignUsed ad where ees.id in (:ees)";
        //noinspection unchecked
        Collection<Long> possibleEEsubsets = ListUtils.removeAll(ees, ee2ads.keySet());
        // note: CollectionUtils.removeAll has a bug.

        qr = session.createQuery(subsetQuery).setParameterList("ees", possibleEEsubsets).list();
        ee2ads = CommonQueries.addAllAds(ee2ads, qr);
    }

    return ee2ads;
}