Example usage for org.hibernate Query setParameterList

List of usage examples for org.hibernate Query setParameterList

Introduction

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

Prototype

Query<R> setParameterList(int position, Object[] values);

Source Link

Usage

From source file:ome.services.query.CollectionCountQueryDefinition.java

License:Open Source License

@Override
protected void buildQuery(Session session) throws HibernateException, SQLException {
    String s_field = (String) value("field"); // TODO Generics??? if not
    // in arrays!
    String s_target = LsidUtils.parseType(s_field);
    String s_collection = LsidUtils.parseField(s_field);
    String s_query = String.format(
            "select target.id, count(collection) from %s target " + "join target.%s collection "
                    + (check("ids") ? "where target.id in (:ids)" : "") + "group by target.id",
            s_target, s_collection);/*from   w ww  . j  a va2  s  .  c  om*/

    org.hibernate.Query q = session.createQuery(s_query);
    if (check("ids")) {
        q.setParameterList("ids", (Collection) value("ids"));
    }
    setQuery(q);

}

From source file:ome.services.query.PojosLoadHierarchyQueryDefinition.java

License:Open Source License

@Override
protected void buildQuery(Session session) throws HibernateException, SQLException {

    Class klass = (Class) value(CLASS);

    StringBuilder sb = new StringBuilder();
    if (Project.class.isAssignableFrom(klass)) {
        sb.append("select this from Project this ");
        sb.append("left outer join fetch this.datasetLinks pdl ");
        sb.append("left outer join fetch pdl.child ds ");
        if (params.isLeaves()) {
            sb.append("left outer join fetch ds.imageLinks dil ");
            sb.append("left outer join fetch dil.child img ");
        }/*from   ww  w.j  a v a2 s .  c o  m*/
        sb.append("left outer join fetch " + "this.annotationLinksCountPerOwner this_a_c ");
    } else if (Dataset.class.isAssignableFrom(klass)) {
        sb.append("select this from Dataset this ");
        if (params.isLeaves()) {
            sb.append("left outer join fetch this.imageLinks dil ");
            sb.append("left outer join fetch dil.child img ");
        }
        sb.append("left outer join fetch " + "this.annotationLinksCountPerOwner this_a_c ");
        sb.append("left outer join fetch " + "this.imageLinksCountPerOwner this_i_c ");
    } else if (Screen.class.isAssignableFrom(klass)) {
        sb.append("select this from Screen this ");
        sb.append("left outer join fetch this.plateLinks pdl ");
        sb.append("left outer join fetch pdl.child ds ");
        sb.append("left outer join fetch ds.details.updateEvent ");
        sb.append("left outer join fetch ds.plateAcquisitions sa ");
        sb.append("left outer join fetch " + "this.annotationLinksCountPerOwner this_a_c ");
        sb.append("left outer join fetch sa.annotationLinksCountPerOwner sa_a_c ");
    } else if (Plate.class.isAssignableFrom(klass)) {
        sb.append("select this from Plate this ");
        sb.append("left outer join fetch this.plateAcquisitions sa ");
        sb.append("left outer join fetch " + "this.annotationLinksCountPerOwner this_a_c ");
        sb.append("left outer join fetch sa.annotationLinksCountPerOwner sa_a_c ");
    } else {
        throw new ApiUsageException("Unknown container class: " + klass.getName());
    }

    if (params.isLeaves()) {
        if (Screen.class.isAssignableFrom(klass) || Plate.class.isAssignableFrom(klass)) {
            sb.append("left outer join fetch sa.wellSample ws ");
            sb.append("left outer join fetch ws.image img ");
        }
        sb.append("left outer join fetch img.details.updateEvent as evt ");
        sb.append("left outer join fetch img.pixels as pix ");
        sb.append("left outer join fetch img.format as format ");
        sb.append("left outer join fetch pix.pixelsType as pt ");
        if (params.isAcquisitionData()) {
            sb.append("left outer join fetch img.stageLabel as position ");
            sb.append("left outer join fetch img.imagingEnvironment" + " as condition ");
            sb.append("left outer join fetch img.objectiveSettings as os ");
            sb.append("left outer join fetch os.medium as me ");
            sb.append("left outer join fetch os.objective as objective ");
            sb.append("left outer join fetch objective.immersion as im ");
            sb.append("left outer join fetch objective.correction as co ");
        }
    }

    // optional ids
    Collection ids = (Collection) value(IDS);
    if (ids != null && ids.size() > 0) {
        sb.append("where this.id in (:ids)");
    }

    org.hibernate.Query q = session.createQuery(sb.toString());
    if (ids != null && ids.size() > 0) {
        q.setParameterList("ids", ids);
    }
    setQuery(q);
}

From source file:ome.services.query.StringQuery.java

License:Open Source License

@Override
protected void buildQuery(Session session) throws HibernateException, SQLException {

    String queryString = (String) value(STRING);
    if (sql != null) {
        for (String key : params.keySet()) {
            if (STRING.equals(key)) {
                continue; // Skip ::string: since its what it is.
            }/*from   ww  w.j ava 2s .c o  m*/
            queryString = sql.rewriteHql(queryString, key, value(key));
        }
    }

    org.hibernate.Query query;
    try {
        query = session.createQuery(queryString);
    } catch (Exception e) {
        // Caused by a query parser error in Hibernate.
        throw new QueryException("Illegal query:" + value(STRING) + "\n" + e.getMessage());
    }
    String[] nParams = query.getNamedParameters();
    for (int i = 0; i < nParams.length; i++) {
        String p = nParams[i];
        Object v = value(p);
        if (v == null) {
            throw new ApiUsageException("Null parameters not allowed: " + p);
        }
        if (Collection.class.isAssignableFrom(v.getClass())) {
            query.setParameterList(p, (Collection) v);
        } else {
            query.setParameter(p, v);
        }
    }

    setQuery(query);
}

From source file:ome.services.sharing.BlobShareStore.java

License:Open Source License

/**
 * Returns a list of data from all shares.
 * //from  w w w  .ja  v a  2 s.  co  m
 * @return
 */
@SuppressWarnings("unchecked")
private Map<Long, byte[]> data(List<Long> ids) {
    Session session = session();
    Query q = session.createQuery("select id, data from Share where id in (:ids)");
    q.setParameterList("ids", ids);
    List<Object[]> data = q.list();
    Map<Long, byte[]> rv = new HashMap<Long, byte[]>();
    for (Object[] objects : data) {
        rv.put((Long) objects[0], (byte[]) objects[1]);
    }
    return rv;
}

From source file:ome.tools.hibernate.QueryBuilder.java

License:Open Source License

private Query __query(Session session, boolean usefilter) {

    if (usefilter) {
        filterNow();/*from www.ja v  a  2s. c  o m*/
    }

    Query q = null;
    try {
        final String s = queryString();
        if (sqlQuery) {
            // ticket:9435 - in order to allow updates with raw
            // SQL we will unwrap the session. This is the only
            // location that is doing such unwrapping.
            // Also see ticket:9496 about deleting rdefs.
            if (s.startsWith("update") || s.startsWith("delete")) {
                if (session instanceof Advised) {
                    Advised proxy = (Advised) session;
                    try {
                        session = (Session) proxy.getTargetSource().getTarget();
                    } catch (Exception e) {
                        RuntimeException rt = new RuntimeException(e);
                        rt.initCause(e);
                        throw rt;
                    }
                }
            }
            q = session.createSQLQuery(queryString());
        } else {
            q = session.createQuery(queryString());
        }
    } catch (RuntimeException rt) {
        // We're logging failed queries because the almost always point
        // to an internal exception that shouldn't be happening.
        log.warn("Failed query: " + queryString(), rt);
        throw rt;
    }

    for (String key : params.keySet()) {
        q.setParameter(key, params.get(key));
    }
    for (Integer key : seqParams.keySet()) {
        q.setParameter(key, seqParams.get(key));
    }
    for (String key : listParams.keySet()) {
        q.setParameterList(key, listParams.get(key));
    }
    if (filter != null) {
        if (filter.limit != null) {
            q.setMaxResults(filter.limit);
        }
        if (filter.offset != null) {
            q.setFirstResult(filter.offset);
        }
    }
    return q;
}

From source file:org.alfresco.repo.workflow.jbpm.JBPMEngine.java

License:Open Source License

@SuppressWarnings({ "unchecked", "cast" })
private void cacheVariablesNoBatch(Session session, List<Long> contextInstanceIds,
        Map<Long, TokenVariableMap> variablesCache) {
    Query query = session.getNamedQuery("org.alfresco.repo.workflow.cacheInstanceVariables");
    query.setParameterList("ids", contextInstanceIds);
    query.setCacheMode(CacheMode.PUT);//  ww  w .j  a va 2s.c o m
    query.setFlushMode(FlushMode.MANUAL);
    query.setCacheable(true);

    List<TokenVariableMap> results = (List<TokenVariableMap>) query.list();
    for (TokenVariableMap tokenVariableMap : results) {
        variablesCache.put(tokenVariableMap.getToken().getId(), tokenVariableMap);
    }
}

From source file:org.ambraproject.rhino.service.taxonomy.impl.TaxonomyClassificationServiceImpl.java

License:Open Source License

private void persistCategories(List<WeightedTerm> terms, Article article) {
    Set<String> termStrings = terms.stream().map(WeightedTerm::getPath).collect(Collectors.toSet());

    Collection<Category> existingCategories = hibernateTemplate.execute(session -> {
        Query query = session.createQuery("FROM Category WHERE path IN (:terms)");
        query.setParameterList("terms", termStrings);
        return (Collection<Category>) query.list();
    });//w w w  .  j  av  a2 s. c o m

    Map<String, Category> existingCategoryMap = Maps.uniqueIndex(existingCategories, Category::getPath);

    Collection<ArticleCategoryAssignment> existingAssignments = getAssignmentsForArticle(article);
    Map<Category, ArticleCategoryAssignment> assignmentMap = Maps.uniqueIndex(existingAssignments,
            ArticleCategoryAssignment::getCategory);
    assignmentMap = new HashMap<>(assignmentMap); // Make it mutable. We will remove assignments as they are updated.

    for (WeightedTerm term : terms) {
        Category category = existingCategoryMap.get(term.getPath());
        if (category == null) {
            /*
             * A new category from the taxonomy server, which is not yet persisted in our system. Create it now.
             *
             * This risks a race condition if two articles are being populated concurrently and both have the same new
             * category, which can cause a "MySQLIntegrityConstraintViolationException: Duplicate entry" error.
             */
            category = new Category();
            category.setPath(term.getPath());
            hibernateTemplate.save(category);
        }

        ArticleCategoryAssignment assignment = assignmentMap.remove(category);
        if (assignment == null) {
            hibernateTemplate.save(new ArticleCategoryAssignment(category, article, term.getWeight()));
        } else {
            assignment.setWeight(term.getWeight());
            hibernateTemplate.update(assignment);
        }
    }

    // Each assignment that was not removed from assignmentMap is not among the new terms, so it should be deleted.
    assignmentMap.values().forEach(hibernateTemplate::delete);
}

From source file:org.ambraproject.service.article.ArticleServiceImpl.java

License:Apache License

@SuppressWarnings("unchecked")
private List<SearchHit> getArticles(final Calendar startDate, final Calendar endDate,
        final List<URI> articleTypesToShow, final String journal_eIssn) {
    // if articleTypesToShow is empty, then all types of articles should be returned

    return (List<SearchHit>) hibernateTemplate.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            //Expected SQL Query:
            //select distinct a.doi, a.title, a.date from article a join articleTypes at on a.articleID = at.articleID
            //where a.eIssn = '%journal_eIssn%' and a.date between '%date%' and '%date%'
            //at.type in ('%article type%', '%article type%')
            String[] types = new String[articleTypesToShow.size()];

            for (int a = 0; a < articleTypesToShow.size(); a++) {
                types[a] = articleTypesToShow.get(a).toString();
            }/*from  w  ww  .  ja v a 2s  .  c o m*/

            String sql = "select distinct a.doi, a.title, a.date "
                    + "from article a join articleType atype on a.articleID = atype.articleID "
                    + "where a.eIssn = :eIssn " + "and a.date between :startDate and :endDate ";

            if (articleTypesToShow.size() > 0) {
                sql = sql + "and atype.type in :types ";
            }
            sql = sql + "order by a.date desc";

            Query query = session.createSQLQuery(sql).setString("eIssn", journal_eIssn)
                    .setCalendar("startDate", startDate).setCalendar("endDate", endDate);

            if (articleTypesToShow.size() > 0) {
                query.setParameterList("types", types);
            }

            List<Object[]> articleResults = query.list();
            List<SearchHit> searchResults = new ArrayList<SearchHit>();

            for (int i = 0; i < articleResults.size(); i++) {
                Object[] res = articleResults.get(i);
                String doi = (String) res[0];
                String title = (String) res[1];
                Date pubDate = (Date) res[2];

                searchResults.add(SearchHit.builder().setUri(doi).setTitle(title).setDate(pubDate).build());
            }

            return searchResults;
        }
    });
}

From source file:org.andromda.timetracker.domain.crud.TaskManageableDaoBase.java

/**
 * @param ids/*  ww w .j  av  a  2 s  .  com*/
 */
public void delete(Long[] ids) {
    final Session session = getSession(false);
    try {
        final Query queryObject = session.createQuery("delete TaskImpl where id in (:ids)");
        queryObject.setParameterList("ids", ids);
        queryObject.executeUpdate();
    } catch (HibernateException ex) {
        throw super.convertHibernateAccessException(ex);
    }
}

From source file:org.andromda.timetracker.domain.crud.UserManageableDaoBase.java

/**
 * @param ids//from w w  w  .j  a  va 2 s .  c  om
 */
public void delete(Long[] ids) {
    final Session session = getSession(false);
    try {
        final Query queryObject = session.createQuery("delete UserImpl where id in (:ids)");
        queryObject.setParameterList("ids", ids);
        queryObject.executeUpdate();
    } catch (HibernateException ex) {
        throw super.convertHibernateAccessException(ex);
    }
}