Example usage for org.hibernate Query setParameters

List of usage examples for org.hibernate Query setParameters

Introduction

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

Prototype

@Deprecated
@SuppressWarnings("unchecked")
default Query<R> setParameters(Object[] values, Type[] types) 

Source Link

Document

Bind values and types to positional parameters.

Usage

From source file:com.rosy.bill.dao.hibernate.SimpleHibernateDao.java

License:Apache License

/**
 * ?SQL?Query.//from   w  w  w .j  a  v  a2  s . com
 * find()???.
 * 
 * @param values .
 * @param queryString
 * @param values ??
 * @param types  ??
 * @return
 */
public Query createSqlQuery(final String queryString, final Object[] values, final Type... types) {
    Assert.hasText(queryString, "queryString?");
    Query query = getSession().createSQLQuery(queryString);
    if (values != null) {

        query.setParameters(values, types);
    }
    return query;
}

From source file:org.bindgen.wicket.phonebook.HibernateContactDao.java

License:Apache License

/**
 * builds a query object to satisfy the provided parameters
 *
 * @param qp// www. j a  v  a  2  s  .  c  o  m
 *            sorting and paging criteria
 * @param filter
 *            filter criteria
 * @param count
 *            true if this is a query meant to retrieve the number of rows
 * @return query object that satisfies the provided criteria
 */
protected Query buildFindQuery(QueryParam qp, Contact filter, boolean count) {
    HibernateContactFinderQueryBuilder builder = new HibernateContactFinderQueryBuilder();
    builder.setQueryParam(qp);
    builder.setFilter(filter);
    builder.setCount(count);
    Query query = getSession().createQuery(builder.buildHql());
    query.setParameters(builder.getParameters(), builder.getTypes());
    if (!count && qp != null) {
        query.setFirstResult(qp.getFirst()).setMaxResults(qp.getCount());
    }
    return query;
}

From source file:org.olat.core.commons.persistence.DBManager.java

License:Apache License

/**
 * Hibernate Find method. Use this in a transactional context by using your current transaction object.
 * /*from  ww w  . jav  a 2s .c o m*/
 * @param trx The current db transaction
 * @param query The HQL query
 * @param values The object array containing all search values
 * @param types The object array containing all Hibernate datatype of the search values
 */
List find(DBTransaction trx, String query, Object[] values, Type[] types) {
    List li = null;
    try {
        boolean doLog = Tracing.isDebugEnabled(DBManager.class);
        long start = 0;
        if (doLog)
            start = System.currentTimeMillis();
        // old: li = getSession().find(query, values, types);
        Query qu = this.getSession().createQuery(query);
        qu.setParameters(values, types);
        li = qu.list();

        if (doLog) {
            long time = (System.currentTimeMillis() - start);
            logQuery("find (time " + time + ", res " + (li == null ? "null" : "" + li.size()) + ")(trans "
                    + trx.hashCode() + ")", values, types, query);
        }

    } catch (HibernateException e) {
        trx.setErrorAndRollback(e);
        String msg = "Find failed in transaction. Query: " + query + " " + e;
        setError(e);
        throw new DBRuntimeException(msg, e);
    }
    return li;
}

From source file:org.olat.core.commons.persistence.DBManager.java

License:Apache License

int delete(DBTransaction trx, String query, Object[] values, Type[] types) {
    int deleted = 0;

    if (trx.isRolledBack() || trx.isCommitted()) { // some program bug
        throw new DBRuntimeException(
                "cannot delete in a transaction that is rolledback or committed " + values);
    }/*from  www  .ja va 2s .c  o  m*/
    try {
        // old: deleted = getSession().delete(query, values, types);
        Session si = getSession();
        Query qu = si.createQuery(query);
        qu.setParameters(values, types);
        List foundToDel = qu.list();
        deleted = foundToDel.size();
        for (int i = 0; i < deleted; i++) {
            si.delete(foundToDel.get(i));
        }

        if (Tracing.isDebugEnabled(DBManager.class)) {
            logQuery("delete (trans " + trx.hashCode() + ")", values, types, query);
        }
    } catch (HibernateException e) { // we have some error
        trx.setErrorAndRollback(e);
        throw new DBRuntimeException("Could not delete object: " + values, e);
    }
    return deleted;
}

From source file:org.sakaiproject.messagebundle.impl.MessageBundleServiceImpl.java

License:Educational Community License

public int getSearchCount(String searchQuery, String module, String baseName, String locale) {
    List<String> values = new ArrayList<String>();
    List<BasicType> types = new ArrayList<BasicType>();
    StringBuffer queryString = new StringBuffer("");

    try {//  w w w  .j a v  a  2s . c o  m
        if (StringUtils.isNotEmpty(searchQuery)) {
            queryString.append("(defaultValue like ? OR value like ? OR propertyName = ?)");
            values.add("%" + searchQuery + "%");
            values.add("%" + searchQuery + "%");
            values.add(searchQuery);
            types.add(StandardBasicTypes.STRING);
            types.add(StandardBasicTypes.STRING);
            types.add(StandardBasicTypes.STRING);
        }
        if (StringUtils.isNotEmpty(module)) {
            if (queryString.length() > 0) {
                queryString.append(" AND ");
            }
            queryString.append("moduleName = ? ");
            values.add(module);
            types.add(StandardBasicTypes.STRING);

        }
        if (StringUtils.isNotEmpty(baseName)) {
            if (queryString.length() > 0) {
                queryString.append(" AND ");
            }
            queryString.append("baseName = ?");
            values.add(baseName);
            types.add(StandardBasicTypes.STRING);

        }
        if (StringUtils.isNotEmpty(locale)) {
            if (queryString.length() > 0) {
                queryString.append(" AND ");
            }
            queryString.append("locale = ?");
            values.add(locale);
            types.add(StandardBasicTypes.STRING);

        }
        if (queryString.length() > 0) {
            queryString.insert(0, "select count(*) from MessageBundleProperty where ");
        } else {
            queryString.insert(0, "select count(*) from MessageBundleProperty");
        }
        Integer count = null;
        try {
            Query query = getSessionFactory().getCurrentSession().createQuery(queryString.toString());
            query.setParameters(values.toArray(), (Type[]) types.toArray(new Type[types.size()]));
            count = (Integer) query.uniqueResult();
        } catch (HibernateException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return count.intValue();
    } catch (Exception e) {
        logger.error("problem searching the message bundle data", e);
    }
    return 0;
}

From source file:org.squale.jraf.provider.persistence.hibernate.AbstractDAOImpl.java

License:Open Source License

/**
 * Execute la requete en valorisant les parametres. Les paramametres sont passes sous forme de tableau dans l'ordre
 * de la requete. Requte libre en langage OQL ou SQL suivant l'implmentation du moteur d'accs aux donnes. La
 * clause where doit comporter une clause where valide incluant le mot cl <b>Where</b <li>ie: 'where Avion = ?'</li>
 * /*from  w  w  w.j  av a  2s  . co m*/
 * @param session session a utiliser
 * @param lRequete requete HQL executee
 * @param values tableau de valeurs
 * @param types tableau des types
 * @return liste d'objets retrouves
 * @throws JrafDaoException exception
 */
public java.util.List find(ISession session, String lRequete, Object[] values, Type[] types)
        throws JrafDaoException {
    SessionImpl sessionHibernate = (SessionImpl) session;
    List liste = null;
    try {
        Query query = sessionHibernate.getSession().createQuery(lRequete);
        query.setParameters(values, types);
        liste = query.list();
    } catch (Exception e) {
        throwDAOException(e, "find");
    }
    return liste;
}

From source file:org.squale.jraf.provider.persistence.hibernate.AbstractDAOImpl.java

License:Open Source License

/**
 * La construction de la requete utilise la mthode getRequete() pour initialiser le dbut de la clause. Les
 * paramametres sont passes sous forme de tableau dans l'ordre de la requete.
 * //from   ww  w .  java  2s .co m
 * @param session session a utiliser
 * @param whereClause requete HQL executee
 * @param values tableau de valeurs
 * @param types tableau des types
 * @return liste d'objets trouves
 */
public java.util.List findWhere(ISession session, String whereClause, Object[] values, Type[] types)
        throws JrafDaoException {
    SessionImpl sessionHibernate = (SessionImpl) session;
    List liste = null;
    try {
        Query query = sessionHibernate.getSession().createQuery(getRequete() + whereClause);
        query.setParameters(values, types);
        liste = query.list();
    } catch (Exception e) {
        throwDAOException(e, "findWhere");
    }
    return liste;
}

From source file:org.squale.jraf.provider.persistence.hibernate.AbstractDAOImpl.java

License:Open Source License

/**
 * Implmentation spcifique Hibernate<br>
 * Supression d'un sous ensemble selectionn suivant une requete HQL. Si la clause where existe, elle doit etre une
 * clause where valide incluant le mot cl <b>Where</b <li>ie: 'where Avion = ?'</li> Sinon, elle peut tre nulle
 * dans ce cas il s'agit d'un delete */*from w ww  .  j  av  a2  s .c  om*/
 * 
 * @param session
 * @param whereClause clause where de la requete HQL.
 * @param values Tableau des valeurs des parametres de la requete
 * @param types Tableau des types des parametres de la requete
 * @return nombre d'instance supprime
 * @throws JrafDaoException
 */
public int removeWhere(ISession session, String whereClause, Object[] values, Type[] types)
        throws JrafDaoException {
    SessionImpl sessionHibernate = (SessionImpl) session;
    String req = "delete " + getClassName(getBusinessClass()) + " " + getAlias() + " ";
    int nbInstanceSupprime = 0;
    try {
        Query query = sessionHibernate.getSession().createQuery(req + whereClause);
        query.setParameters(values, types);
        nbInstanceSupprime = query.executeUpdate();

    } catch (Exception e) {
        throwDAOException(e, "removeAll");
    }
    return nbInstanceSupprime;
}

From source file:sz.fcv.core.db.HQLExecuter.java

License:Open Source License

/**
 * Chiamata dalla classe figlia per eseguire una query hql
 * //from  w ww  .j  av  a  2s .  com
 * @param s Sessione, null per nuova sessione
 * @param hql 
 * @param os
 * @param types 
 * 
 * @throws java.io.FileNotFoundException
 * 
 * @return lista oggetti risultanti
 */
public static List executeHQLQuery(Session s, String hql, Object[] os, Type[] types)
        throws HibernateException, FileNotFoundException, IOException {

    Session session;
    if (s != null) {
        session = s;
    } else {
        session = createSession();
    }

    Query q = session.createQuery(openSQLFile(hql));

    // System.out.println("Esecuzione query: " + q);

    if (os != null) {
        q.setParameters(os, types);
    }

    List resultList = q.list();

    if (s == null) {
        commitSession(session);
    }

    return resultList;
}

From source file:sz.fcv.core.db.HQLExecuter.java

License:Open Source License

/**
 * Esecuzione di una query SQL/*from  ww w.j a  v a2 s . c o  m*/
 * 
 * @param s
 * @param sql
 * @param os
 * @param types
 * @return
 * @throws HibernateException
 * @throws FileNotFoundException
 * @throws IOException 
 */
public static List executeSQLQuery(Session s, String sql, Object[] os, Type[] types)
        throws HibernateException, FileNotFoundException, IOException {
    Session session;
    if (s != null) {
        session = s;
    } else {
        session = createSession();
    }

    Query q = session.createSQLQuery(openSQLFile(sql));

    if (os != null) {
        q.setParameters(os, types);
    }

    List resultList = q.list();

    if (s == null) {
        commitSession(session);
    }

    return resultList;
}