Example usage for org.hibernate Query getNamedParameters

List of usage examples for org.hibernate Query getNamedParameters

Introduction

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

Prototype

@Deprecated
String[] getNamedParameters();

Source Link

Document

Return the names of all named parameters of the query.

Usage

From source file:it.cilea.osd.common.dao.impl.GenericDaoHibernateImpl.java

License:Open Source License

/**
 * We support only named query without named parameter OR with only named
 * parameter named like par<idx>
 * /*from   w ww.  j  a v  a  2 s .  co m*/
 * @param method
 * @param querySuffixes
 * @param queryArgs
 * @return
 */
private Query buildQuery(Method method, String[] querySuffixes, Object[] queryArgs) {
    StringBuffer sb = new StringBuffer();
    sb.append(type.getSimpleName()).append('.').append(method.getName());
    if (querySuffixes != null) {
        for (int i = 0; i < querySuffixes.length; i++) {
            sb.append('.').append(querySuffixes[i]);
        }
    }
    String queryName = new String(sb);
    Query namedQuery = getSession().getNamedQuery(queryName);
    String[] namedParameters = namedQuery.getNamedParameters();

    if (namedParameters.length > 0) {
        for (int i = 0; i < namedParameters.length; i++) {
            Object arg = queryArgs[i];
            if (arg instanceof Collection) {

                namedQuery.setParameterList("par" + i, (Collection) arg);
            } else {

                namedQuery.setParameter("par" + i, arg);
            }
        }
    } else if (queryArgs != null) {
        for (int i = 0; i < queryArgs.length; i++) {
            Object arg = queryArgs[i];
            namedQuery.setParameter(i, arg);
        }
    }
    return namedQuery;
}

From source file:nl.strohalm.cyclos.utils.hibernate.HibernateQueryHandler.java

License:Open Source License

/**
 * Sets the query bind named parameters//from   w  ww .  java  2 s.  c o m
 */
public void setQueryParameters(final Query query, final Object parameters) {
    if (parameters != null) {
        if (parameters instanceof Map<?, ?>) {
            final Map<?, ?> map = (Map<?, ?>) parameters;
            final String[] paramNames = query.getNamedParameters();
            for (final String param : paramNames) {
                final Object value = map.get(param);
                if (value instanceof Collection<?>) {
                    final Collection<Object> values = new ArrayList<Object>(((Collection<?>) value).size());
                    for (final Object object : (Collection<?>) value) {
                        if (object instanceof EntityReference) {
                            values.add(fetchDao.fetch((Entity) object));
                        } else {
                            values.add(object);
                        }
                    }
                    query.setParameterList(param, values);
                } else if (value instanceof EntityReference) {
                    query.setParameter(param, fetchDao.fetch((Entity) value));
                } else {
                    query.setParameter(param, value);
                }
            }
        } else {
            query.setProperties(parameters);
        }
    }
}

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.
            }/*  w w w  .  j  ava2s  .  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:org.anyframe.hibernate.impl.DynamicHibernateServiceImpl.java

License:Apache License

/**
 * The internal method for replacing by the inputted values the phrases
 * handled by variables and finding the appropriate HQL phrases by the
 * identifier of dynamic HQL defined in a separate XML.
 * /*from   w  ww  .j a  v  a2s .  c o  m*/
 * @param session
 *            the hibernate session to create query
 * @param queryName
 *            executable dynamic HQL's identifier
 * @param context
 *            velocity context
 * @return query instance set with parameter
 * @throws IOException
 *             for the query instance, there is a problem while setting the
 *             parameter
 */
private Query findInternal(Session session, String queryName, Context context) throws IOException {
    if (context == null)
        context = new VelocityContext();
    QueryInfo info = queries.get(queryName);

    // text replacement
    String sql = getRunnableSQL(info.getStatement(), context);

    StringWriter writer = new StringWriter();
    Velocity.evaluate(context, writer, "Hibernate", sql);
    sql = writer.toString();

    Query query = null;

    if (info.getType().equals("hql")) {
        query = session.createQuery(sql);
    } else {
        query = session.createSQLQuery(sql);

        addEntity((SQLQuery) query, info.getReturnList());
        addJoin((SQLQuery) query, info.getReturnJoinMap());
        addScalar((SQLQuery) query, info.getReturnScalarMap());
    }

    String[] namedParams = query.getNamedParameters();
    for (int i = 0; i < namedParams.length; i++) {
        String namedParam = namedParams[i];
        query.setParameter(namedParam, context.get(namedParam));
    }

    return query;
}

From source file:org.codehaus.grepo.query.hibernate.generator.QueryGeneratorBase.java

License:Apache License

/**
 * Applies the query parameters (named or positional) for the given {@code query}.
 *
 * @param qmpi The query method parameter info.
 * @param context The context./*from   w  w w  . j a v a  2s .c  o m*/
 * @param query The query.
 */
protected void applyQueryParameters(QueryMethodParameterInfo qmpi, HibernateQueryExecutionContext context,
        Query query) {
    String[] namedParameters = query.getNamedParameters();
    if (namedParameters.length > 0) {
        setNamedParameters(qmpi, namedParameters, context, query);
    } else {
        setPositionalParameters(qmpi, context, query);
    }
}

From source file:org.mifos.platform.persistence.support.GenericDaoHibernateImpl.java

License:Open Source License

@Override
public List<T> execFindQuery(String qryMethodName, Object[] queryArgs) {
    Query namedQuery = getSession().getNamedQuery(type.getSimpleName() + "." + qryMethodName);
    if (namedQuery.getNamedParameters().length == 0) {
        setParamsOnNamedQuery(queryArgs, namedQuery);
    } else {// ww w  . j  ava2s . c  o  m
        setArgsOnNamedQuery(queryArgs, namedQuery);
    }
    return namedQuery.list();
}

From source file:org.mifos.platform.persistence.support.GenericDaoHibernateImpl.java

License:Open Source License

private void setArgsOnNamedQuery(Object[] queryArgs, Query namedQuery) {
    if (queryArgs != null) {
        String[] namedParameters = namedQuery.getNamedParameters();
        for (int i = 0; i < queryArgs.length; i++) {
            Object arg = queryArgs[i];
            if (arg instanceof Collection) {
                namedQuery.setParameterList(namedParameters[i], (Collection) arg);
            } else {
                namedQuery.setParameter(namedParameters[i], arg);
            }//from   w  ww. j  a v a2 s  . c o m
        }
    }
}

From source file:org.openbravo.client.querylist.QueryListDataSource.java

License:Open Source License

@Override
protected List<Map<String, Object>> getData(Map<String, String> parameters, int startRow, int endRow) {
    // creation of formats is done here because they are not thread safe
    final SimpleDateFormat xmlDateFormat = JsonUtils.createDateFormat();
    final SimpleDateFormat xmlDateTimeFormat = JsonUtils.createDateTimeFormat();

    OBContext.setAdminMode();/*w w  w .  jav  a  2 s . c o  m*/
    try {
        WidgetClass widgetClass = OBDal.getInstance().get(WidgetClass.class, parameters.get("widgetId"));

        // Check security: continue only if the widget instance is visible for current user/role
        WidgetInstance wi = OBDal.getInstance().get(WidgetInstance.class, parameters.get("widgetInstanceId"));

        boolean accessibleWidgetInForm = false;
        if (wi == null) {
            accessibleWidgetInForm = isAccessibleWidgetInForm(widgetClass);
        }
        if (!accessibleWidgetInForm && (wi == null || wi.getWidgetClass().getId() != widgetClass.getId())) {
            // weird stuff: widget class doesn't match widget instance's class, most probably URL is
            // not generated by UI, but user is typing it
            log.error("User " + OBContext.getOBContext().getUser() + " with role "
                    + OBContext.getOBContext().getRole() + " is trying to access widget '"
                    + widgetClass.getWidgetTitle() + "' but widget istance doesn't match with class");
            throw new OBSecurityException(OBMessageUtils.getI18NMessage("OBCQL_NoAccessToWidget",
                    new String[] { widgetClass.getWidgetTitle() }));
        }

        if (!accessibleWidgetInForm && (OBContext.getOBContext() != null
                && ((wi.getVisibleAtUser() != null
                        && !wi.getVisibleAtUser().getId().equals(OBContext.getOBContext().getUser().getId())))
                || (wi.getVisibleAtRole() != null && !wi.getVisibleAtRole().getId()
                        .equals(OBContext.getOBContext().getRole().getId())))) {
            log.error("User " + OBContext.getOBContext().getUser() + " with role "
                    + OBContext.getOBContext().getRole() + " is trying to access widget '"
                    + widgetClass.getWidgetTitle() + "' which is not granted");
            throw new OBSecurityException(OBMessageUtils.getI18NMessage("OBCQL_NoAccessToWidget",
                    new String[] { widgetClass.getWidgetTitle() }));
        }

        boolean isExport = "true".equals(parameters.get("exportToFile"));
        boolean showAll = "true".equals(parameters.get("showAll"));
        String viewMode = parameters.get("viewMode");
        List<OBCQL_QueryColumn> columns = QueryListUtils
                .getColumns(widgetClass.getOBCQLWidgetQueryList().get(0));

        // handle complex criteria
        try {
            JSONArray criterias = (JSONArray) JsonUtils.buildCriteria(parameters).get("criteria");
            for (int i = 0; i < criterias.length(); i++) {
                final JSONObject criteria = criterias.getJSONObject(i);
                parameters.put(criteria.getString("fieldName"), criteria.getString("value"));
                parameters.put(criteria.getString("fieldName") + OPERATOR, criteria.getString("operator"));
            }
        } catch (JSONException e) {
            // Ignore exception.
        }

        OBCQL_WidgetQuery widgetQueryInstance = widgetClass.getOBCQLWidgetQueryList().get(0);
        String HQL = widgetQueryInstance.getHQL();
        // Parse the HQL in case that optional filters are required
        HQL = parseOptionalFilters(HQL, viewMode, parameters, columns, xmlDateFormat);
        boolean fetchingSummaryFields = parameters.containsKey(JsonConstants.SUMMARY_PARAMETER);
        if (fetchingSummaryFields) {
            // if the request comes from the summary row, update the select clause so that it obtains
            // the values for the summary fields
            HQL = updateHQLWithSummaryFields(HQL, parameters.get(JsonConstants.SUMMARY_PARAMETER),
                    widgetQueryInstance);
        }

        if (parameters.containsKey(JsonConstants.SORTBY_PARAMETER)) {
            HQL = updateSortByFields(HQL, parameters.get(JsonConstants.SORTBY_PARAMETER));
        }

        Query widgetQuery = null;
        try {
            widgetQuery = OBDal.getInstance().getSession().createQuery(HQL);
        } catch (Exception e) {
            if (fetchingSummaryFields) {
                log.error("Exception while fetching the summary columns of the widget "
                        + widgetClass.getWidgetTitle()
                        + ". It is not supported using as summaries columns that are defined using a subquery, or that are defined using a summary function. \n Query = "
                        + HQL);
            } else {
                log.error("Exception while executing the HQL query to fetch the data of the widget "
                        + widgetClass.getWidgetTitle() + ". \n Query = " + HQL);
            }
            final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
            return result;
        }
        String[] queryAliases = widgetQuery.getReturnAliases();

        if (!isExport && "widget".equals(viewMode) && !showAll) {
            int rowsNumber = Integer.valueOf(
                    (parameters.get("rowsNumber") != null && !parameters.get("rowsNumber").equals("null"))
                            ? parameters.get("rowsNumber")
                            : "10");
            widgetQuery.setMaxResults(rowsNumber);
        } else if (!isExport) {
            if (startRow > 0) {
                widgetQuery.setFirstResult(startRow);
            }
            if (endRow > startRow) {
                widgetQuery.setMaxResults(endRow - startRow + 1);
            }
        }

        String[] params = widgetQuery.getNamedParameters();
        if (params.length > 0) {
            HashMap<String, Object> parameterValues = getParameterValues(parameters, widgetClass);

            for (int i = 0; i < params.length; i++) {
                String namedParam = params[i];
                boolean isParamSet = false;
                if (parameterValues.containsKey(namedParam)) {
                    Object value = parameterValues.get(namedParam);
                    if (value instanceof Collection<?>) {
                        widgetQuery.setParameterList(namedParam, (Collection<?>) value);
                    } else if (value instanceof Object[]) {
                        widgetQuery.setParameterList(namedParam, (Object[]) value);
                    } else if (value instanceof String
                            && isDate(namedParam, widgetClass.getOBUIAPPParameterEMObkmoWidgetClassIDList())) {
                        widgetQuery.setParameter(namedParam, convertToDate((String) value));
                    } else {
                        widgetQuery.setParameter(namedParam, value);
                    }
                    isParamSet = true;
                }
                if (!isParamSet) {
                    // TODO: throw an exception
                }
            }
        }

        final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

        if (fetchingSummaryFields) {
            // process the response for the summary row
            Map<String, Object> summaryData = new LinkedHashMap<String, Object>();
            try {
                JSONObject summaryFieldsObject = new JSONObject(
                        parameters.get(JsonConstants.SUMMARY_PARAMETER));
                Iterator<?> summaryFieldNameIterator = summaryFieldsObject.keys();
                Object uniqueResult = widgetQuery.uniqueResult();
                if (uniqueResult instanceof Object[]) {
                    // handles the case where the values of several summary fields are request
                    Object[] summaryValues = (Object[]) uniqueResult;
                    int i = 0;
                    while (summaryFieldNameIterator.hasNext()) {
                        String summaryFieldName = (String) summaryFieldNameIterator.next();
                        summaryData.put(summaryFieldName, summaryValues[i++]);
                    }
                } else {
                    // handles the case where the value of just one summary field is request
                    String summaryFieldName = (String) summaryFieldsObject.names().get(0);
                    summaryData.put(summaryFieldName, uniqueResult);
                }
                summaryData.put("isGridSummary", true);
            } catch (Exception e) {
            }
            result.add(summaryData);

        } else {
            // process the response for the grid
            for (Object objResult : widgetQuery.list()) {
                final Map<String, Object> data = new LinkedHashMap<String, Object>();
                Object[] resultList = new Object[1];
                if (objResult instanceof Object[]) {
                    resultList = (Object[]) objResult;
                } else {
                    resultList[0] = objResult;
                }

                for (OBCQL_QueryColumn column : columns) {
                    UIDefinition uiDefinition = UIDefinitionController.getInstance()
                            .getUIDefinition(column.getReference());
                    DomainType domainType = uiDefinition.getDomainType();
                    // TODO: throw an exception if the display expression doesn't match any returned alias.
                    for (int i = 0; i < queryAliases.length; i++) {
                        if (queryAliases[i].equals(column.getDisplayExpression())
                                || (!isExport && queryAliases[i].equals(column.getLinkExpression()))) {
                            Object value = resultList[i];
                            if (domainType instanceof DateDomainType || domainType instanceof DateDomainType) {
                                value = xmlDateFormat.format(value);
                            } else if (value instanceof Timestamp) {
                                value = xmlDateTimeFormat.format(value);
                                value = JsonUtils.convertToCorrectXSDFormat((String) value);
                            }

                            if (domainType instanceof BooleanDomainType) {
                                if (value instanceof String) {
                                    value = ((PrimitiveDomainType) domainType).createFromString((String) value);
                                }
                            }

                            if (!isExport) {
                                data.put(queryAliases[i], value);
                            } else {
                                data.put(QueryListUtils.getColumnLabel(column), value);
                            }
                        }
                    }
                }
                result.add(data);
            }
        }
        return result;
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.openmrs.module.dhisreport.api.db.hibernate.HibernateDHIS2ReportingDAO.java

License:Open Source License

@Override
public String evaluateDataValueTemplate(DataValueTemplate dvt, Period period, Location location)
        throws DHIS2ReportingException {
    String queryString = dvt.getQuery();
    if (queryString == null || queryString.isEmpty()) {
        log.debug("Empty query for " + dvt.getDataelement().getName() + " : "
                + dvt.getDisaggregation().getName());
        return null;
    }// w  ww  . jav a2 s  .  c o  m

    if (dvt.potentialUpdateDelete()) {
        throw new DHIS2ReportingException("Attempt to execute potential update/delete query for "
                + dvt.getDataelement().getName() + " : " + dvt.getDisaggregation().getName());
    }

    Query query = sessionFactory.getCurrentSession().createSQLQuery(queryString);

    List<String> parameters = new ArrayList<String>(Arrays.asList(query.getNamedParameters()));
    // loactionId is optional
    if (parameters.contains("locationId")) {
        query.setParameter("locationId", location.getId().toString());
    }
    query.setParameter("startOfPeriod", period.getStart());
    query.setParameter("endOfPeriod", period.getEnd());

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

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.hibernate.SimpleHQLDataFactory.java

License:Open Source License

/**
 * Queries a datasource. The string 'query' defines the name of the query. The Parameterset given here may contain
 * more data than actually needed.//from   w  w w .ja va2 s.c om
 * <p/>
 * The dataset may change between two calls, do not assume anything!
 *
 * @param query
 * @param parameters
 * @return
 */
public synchronized TableModel queryData(final String query, final DataRow parameters)
        throws ReportDataFactoryException {
    try {
        final Query pstmt = getSession().createQuery(query);
        final String[] params = pstmt.getNamedParameters();
        for (int i = 0; i < params.length; i++) {
            final String param = params[i];
            final Object pvalue = parameters.get(param);
            if (pvalue == null) {
                // this should work, but some driver are known to die here.
                // they should be fed with setNull(..) instead; something
                // we cant do as JDK1.2's JDBC does not define it.
                pstmt.setParameter(param, null);
            } else {
                pstmt.setParameter(param, pvalue);
            }
        }

        final Object queryLimit = parameters.get(DataFactory.QUERY_LIMIT);
        if (queryLimit instanceof Number) {
            final Number i = (Number) queryLimit;
            if (i.intValue() >= 0) {
                pstmt.setMaxResults(i.intValue());
            }
        }
        final Object queryTimeout = parameters.get(DataFactory.QUERY_TIMEOUT);
        if (queryTimeout instanceof Number) {
            final Number i = (Number) queryLimit;
            if (i.intValue() >= 0) {
                pstmt.setTimeout(i.intValue());
            }
        }
        final ScrollableResults res = pstmt.scroll(ScrollMode.FORWARD_ONLY);
        return generateDefaultTableModel(res, pstmt.getReturnAliases());
    } catch (Exception e) {
        throw new ReportDataFactoryException("Failed at query: " + query, e);
    }
}