Example usage for org.hibernate SQLQuery addScalar

List of usage examples for org.hibernate SQLQuery addScalar

Introduction

In this page you can find the example usage for org.hibernate SQLQuery addScalar.

Prototype

SQLQuery<T> addScalar(String columnAlias);

Source Link

Document

Declare a scalar query result.

Usage

From source file:com.exilant.GLEngine.CoaCache.java

License:Open Source License

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void loadAccountData() {

    /*//from ww  w.  ja va 2 s .c  o  m
     * 1.Loads all the account codes and details of that as GLAccount objects in theGLAccountCode,theGLAccountId HashMap's
     */

    // Temporary place holders
    final HashMap glAccountCodes = new HashMap();
    final HashMap glAccountIds = new HashMap();
    final HashMap accountDetailType = new HashMap();

    String sql = "select id as \"id\",name as \"name\",tableName as \"tableName\","
            + "description as \"description\",columnName as \"columnName\",attributeName as \"attributeName\""
            + ",nbrOfLevels as  \"nbrOfLevels\" from AccountDetailType";

    final Session currentSession = persistenceService.getSession();
    SQLQuery createSQLQuery = currentSession.createSQLQuery(sql);
    createSQLQuery.addScalar("id", IntegerType.INSTANCE).addScalar("name").addScalar("tableName")
            .addScalar("description").addScalar("columnName").addScalar("attributeName")
            .setResultTransformer(Transformers.aliasToBean(AccountDetailType.class));
    List<AccountDetailType> accountDetailTypeList = new ArrayList<AccountDetailType>();
    List<GLAccount> glAccountCodesList = new ArrayList<GLAccount>();
    new ArrayList<GLAccount>();

    accountDetailTypeList = createSQLQuery.list();
    for (final AccountDetailType type : accountDetailTypeList)
        accountDetailType.put(type.getAttributeName(), type);
    sql = "select ID as \"ID\", glCode as \"glCode\" ,name as \"name\" ,"
            + "isActiveForPosting as \"isActiveForPosting\" ,classification as \"classification\", functionReqd as \"functionRequired\" from chartofaccounts ";
    createSQLQuery = currentSession.createSQLQuery(sql);
    createSQLQuery.addScalar("ID", IntegerType.INSTANCE).addScalar("glCode").addScalar("name")
            .addScalar("isActiveForPosting", BooleanType.INSTANCE)
            .addScalar("classification", LongType.INSTANCE).addScalar("functionRequired", BooleanType.INSTANCE)
            .setResultTransformer(Transformers.aliasToBean(GLAccount.class));

    glAccountCodesList = createSQLQuery.list();
    for (final GLAccount type : glAccountCodesList)
        glAccountCodes.put(type.getCode(), type);
    for (final GLAccount type : glAccountCodesList)
        glAccountIds.put(type.getId(), type);
    loadParameters(glAccountCodes, glAccountIds);
    try {
        final HashMap<String, HashMap> hm = new HashMap<String, HashMap>();
        hm.put(ACCOUNTDETAILTYPENODE, accountDetailType);
        hm.put(GLACCCODENODE, glAccountCodes);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Loading size:" + glAccountCodes.size());
        hm.put(GLACCIDNODE, glAccountIds);
        applicationCacheManager.put(ROOTNODE, hm);
    } catch (final Exception e) {
        throw e;
    }

}

From source file:com.impetus.client.rdbms.HibernateClient.java

License:Apache License

/**
 * Gets the query instance./*from   ww w .  j  av a2 s . c om*/
 * 
 * @param nativeQuery
 *            the native query
 * @param m
 *            the m
 * @return the query instance
 */
public SQLQuery getQueryInstance(String nativeQuery, EntityMetadata m) {
    s = getStatelessSession();

    SQLQuery q = s.createSQLQuery(nativeQuery).addEntity(m.getEntityClazz());

    List<String> relations = m.getRelationNames();
    if (relations != null) {
        for (String r : relations) {
            Relation rel = m.getRelation(m.getFieldName(r));
            String name = MetadataUtils.getMappedName(m, m.getRelation(r), kunderaMetadata);
            if (!((AbstractAttribute) m.getIdAttribute()).getJPAColumnName()
                    .equalsIgnoreCase(name != null ? name : r) && rel != null
                    && !rel.getProperty().isAnnotationPresent(ManyToMany.class)
                    && !rel.getProperty().isAnnotationPresent(OneToMany.class)
                    && (rel.getProperty().isAnnotationPresent(OneToOne.class)
                            && StringUtils.isBlank(rel.getMappedBy())
                            || rel.getProperty().isAnnotationPresent(ManyToOne.class))) {
                q.addScalar(name != null ? name : r);
            }
        }
    }
    return q;
}

From source file:com.querydsl.jpa.hibernate.sql.AbstractHibernateSQLQuery.java

License:Apache License

private Query createQuery(boolean forCount) {
    NativeSQLSerializer serializer = (NativeSQLSerializer) serialize(forCount);
    String queryString = serializer.toString();
    logQuery(queryString, serializer.getConstantToLabel());
    org.hibernate.SQLQuery query = session.createSQLQuery(queryString);
    // set constants
    HibernateUtil.setConstants(query, serializer.getConstantToLabel(), queryMixin.getMetadata().getParams());

    if (!forCount) {
        ListMultimap<Expression<?>, String> aliases = serializer.getAliases();
        Set<String> used = Sets.newHashSet();
        // set entity paths
        Expression<?> projection = queryMixin.getMetadata().getProjection();
        if (projection instanceof FactoryExpression) {
            for (Expression<?> expr : ((FactoryExpression<?>) projection).getArgs()) {
                if (isEntityExpression(expr)) {
                    query.addEntity(extractEntityExpression(expr).toString(), expr.getType());
                } else if (aliases.containsKey(expr)) {
                    for (String scalar : aliases.get(expr)) {
                        if (!used.contains(scalar)) {
                            query.addScalar(scalar);
                            used.add(scalar);
                            break;
                        }/*from  w  w w  .j av a  2 s.  com*/
                    }
                }
            }
        } else if (isEntityExpression(projection)) {
            query.addEntity(extractEntityExpression(projection).toString(), projection.getType());
        } else if (aliases.containsKey(projection)) {
            for (String scalar : aliases.get(projection)) {
                if (!used.contains(scalar)) {
                    query.addScalar(scalar);
                    used.add(scalar);
                    break;
                }
            }
        }

        // set result transformer, if projection is a FactoryExpression instance
        if (projection instanceof FactoryExpression) {
            query.setResultTransformer(new FactoryExpressionTransformer((FactoryExpression<?>) projection));
        }
    }

    if (fetchSize > 0) {
        query.setFetchSize(fetchSize);
    }
    if (timeout > 0) {
        query.setTimeout(timeout);
    }
    if (cacheable != null) {
        query.setCacheable(cacheable);
    }
    if (cacheRegion != null) {
        query.setCacheRegion(cacheRegion);
    }
    if (readOnly != null) {
        query.setReadOnly(readOnly);
    }
    return query;
}

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

License:Apache License

protected void applyAddScalarSetting(String columnAlias, Type type, SQLQuery query) {
    if (type == null) {
        query.addScalar(columnAlias);
    } else {/* w ww .j  av a 2 s.  c o m*/
        query.addScalar(columnAlias, type);
    }
}

From source file:org.egov.egf.web.actions.brs.AutoReconcileHelper.java

License:Open Source License

private List<AutoReconcileBean> getStatmentsForProcessing(final String type) {
    final SQLQuery detailQuery = persistenceService.getSession()
            .createSQLQuery("select id,txDate,instrumentNo,debit,credit,CSLno  from " + TABLENAME
                    + " where accountId=:accountId  and type='" + type + "' and action='"
                    + BRS_ACTION_TO_BE_PROCESSED + "'");
    detailQuery.setLong("accountId", accountId);
    detailQuery.addScalar("id", LongType.INSTANCE).addScalar("txDate").addScalar("instrumentNo")
            .addScalar("debit").addScalar("credit").addScalar("CSLno")
            .setResultTransformer(Transformers.aliasToBean(AutoReconcileBean.class));
    final List<AutoReconcileBean> detailList = detailQuery.list();
    return detailList;
}

From source file:org.egov.egf.web.actions.voucher.CommonAction.java

License:Open Source License

@Action(value = "/voucher/common-ajaxLoadProjectCodesForSubScheme")
public String ajaxLoadProjectCodesForSubScheme() {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting ajaxLoadProjectCodesForSubScheme...");
    final String sql = "select pc.id as id,pc.code as code,pc.name as name from egw_projectcode pc,egf_subscheme_project ssp where  pc.id=ssp.projectcodeid and ssp.subschemeid="
            + subSchemeId;//from   w  w w .  ja va2  s  .com
    final SQLQuery pcQuery = persistenceService.getSession().createSQLQuery(sql);
    pcQuery.addScalar("id", LongType.INSTANCE).addScalar("code").addScalar("name")
            .setResultTransformer(Transformers.aliasToBean(LoanGrantBean.class));
    projectCodeList = pcQuery.list();
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed ajaxLoadProjectCodesForSubScheme.");
    return "projectcodes";
}

From source file:org.egov.services.report.IncomeExpenditureService.java

License:Open Source License

private List<StatementResultObject> getBudgetForMajorCodes(final Statement incomeExpenditureStatement) {

    final StringBuilder queryStr = new StringBuilder(1000);

    queryStr.append(" select coa.majorCode as glcode, sum(bd.approvedamount) as amount ").append(
            " from egf_budgetdetail bd , egf_budgetgroup bg,egf_budget b, chartofaccounts coa, eg_wf_states wfs ")
            .append("where ((bg.maxcode<=coa.id and bg.mincode>=coa.id) or bg.majorcode=coa.id ) ")
            .append("and bd.budgetgroup= bg.id and bd.budget=b.id and  bd.state_id=wfs.id  and wfs.value='END'")
            .append("and b.isbere=:isBeRe and b.financialyearid=:finYearId  ");
    if (incomeExpenditureStatement.getFund() != null && incomeExpenditureStatement.getFund().getId() != null
            && incomeExpenditureStatement.getFund().getId() != 0)
        queryStr.append(" and bd.fund=" + incomeExpenditureStatement.getFund().getId());
    if (incomeExpenditureStatement.getDepartment() != null
            && incomeExpenditureStatement.getDepartment().getId() != 0)
        queryStr.append(" and bd.executing_department=" + incomeExpenditureStatement.getDepartment().getId());
    if (incomeExpenditureStatement.getFunction() != null
            && incomeExpenditureStatement.getFunction().getId() != null
            && incomeExpenditureStatement.getFunction().getId() != 0)
        queryStr.append("  and bd.function= " + incomeExpenditureStatement.getFunction().getId());

    queryStr.append(" and coa.majorcode is not null  group by coa.majorCode ");

    queryStr.append(" order by 1");
    final SQLQuery budgteQuery = persistenceService.getSession().createSQLQuery(queryStr.toString());
    budgteQuery.addScalar("glCode").addScalar("amount")
            .setResultTransformer(Transformers.aliasToBean(StatementResultObject.class));
    budgteQuery.setLong("finYearId", incomeExpenditureStatement.getFinancialYear().getId()).setString("isBeRe",
            "RE");
    return budgteQuery.list();

}

From source file:org.egov.services.report.IncomeExpenditureService.java

License:Open Source License

private List<StatementResultObject> getBudgetReappMinorCodes(final Statement incomeExpenditureStatement) {
    final StringBuilder queryStr = new StringBuilder(1000);

    queryStr.append(//from  w  ww .j a  va 2  s .  c om
            " select coa.majorcode as glCode, sum(bdr.addition_amount- bdr.deduction_amount) as amount ")
            .append(" from egf_budgetdetail bd , egf_budgetgroup bg,egf_budget b, chartofaccounts coa,eg_wf_states wfs,")
            .append("egf_budget_reappropriation bdr where ((bg.maxcode<=coa.id and bg.mincode>=coa.id) or bg.majorcode=coa.id ) ")
            .append("and bd.budgetgroup= bg.id and bdr.budgetdetail=bd.id and bd.budget=b.id and bdr.state_id=wfs.id ")
            .append("and wfs.value='END' and b.isbere=:isBeRe and b.financialyearid=:finYearId  ");

    if (incomeExpenditureStatement.getFund() != null && incomeExpenditureStatement.getFund().getId() != null
            && incomeExpenditureStatement.getFund().getId() != 0)
        queryStr.append(" and bd.fund=" + incomeExpenditureStatement.getFund().getId());
    if (incomeExpenditureStatement.getDepartment() != null
            && incomeExpenditureStatement.getDepartment().getId() != 0)
        queryStr.append(" and bd.executing_department=" + incomeExpenditureStatement.getDepartment().getId());
    if (incomeExpenditureStatement.getFunction() != null
            && incomeExpenditureStatement.getFunction().getId() != null
            && incomeExpenditureStatement.getFunction().getId() != 0)
        queryStr.append("  and bd.function= " + incomeExpenditureStatement.getFunction().getId());
    queryStr.append("  group by coa.majorCode ");

    queryStr.append(" order by 1 asc");
    final SQLQuery budgteReappQuery = persistenceService.getSession().createSQLQuery(queryStr.toString());
    budgteReappQuery.addScalar("glCode").addScalar("amount")
            .setResultTransformer(Transformers.aliasToBean(StatementResultObject.class));
    budgteReappQuery.setLong("finYearId", incomeExpenditureStatement.getFinancialYear().getId())
            .setString("isBeRe", "RE");
    return budgteReappQuery.list();
}

From source file:org.generationcp.middleware.dao.dms.DmsProjectDao.java

License:Open Source License

public StudyMetadata getStudyMetadataForGeolocationId(final Integer geolocationId) {
    Preconditions.checkNotNull(geolocationId);
    try {/* www  . ja  va  2  s.  com*/
        final SQLQuery query = this.getSession()
                .createSQLQuery(DmsProjectDao.GET_STUDY_METADATA_BY_GEOLOCATION_ID);
        query.addScalar("studyDbId");
        query.addScalar("trialOrNurseryId");
        query.addScalar("studyName");
        query.addScalar("studyType");
        query.addScalar("seasonId");
        query.addScalar("trialDbId");
        query.addScalar("trialName");
        query.addScalar("startDate");
        query.addScalar("endDate");
        query.addScalar("deleted");
        query.addScalar("locationID");
        query.setParameter("geolocationId", geolocationId);
        final Object result = query.uniqueResult();
        if (result != null) {
            final Object[] row = (Object[]) result;
            final StudyMetadata studyMetadata = new StudyMetadata();
            studyMetadata.setStudyDbId(geolocationId);
            studyMetadata.setNurseryOrTrialId((row[1] instanceof Integer) ? (Integer) row[1] : null);
            studyMetadata.setStudyName((row[2] instanceof String) ? (String) row[2] : null);
            studyMetadata.setStudyType((row[3] instanceof Integer) ? ((Integer) row[3]).toString() : null);
            if (row[4] instanceof String && !StringUtils.isBlank((String) row[4])) {
                studyMetadata.addSeason(TermId.getById(Integer.parseInt((String) row[4])).toString());
            }
            studyMetadata.setTrialDbId((row[5] instanceof Integer) ? (Integer) row[5] : null);
            studyMetadata.setTrialName((row[6] instanceof String) ? (String) row[6] : null);
            studyMetadata.setStartDate((row[7] instanceof String) ? (String) row[7] : null);
            studyMetadata.setEndDate((row[8] instanceof String) ? (String) row[8] : null);
            studyMetadata.setActive(Boolean.FALSE.equals(row[9]));
            studyMetadata
                    .setLocationId((row[10] instanceof String) ? Integer.parseInt((String) row[10]) : null);
            return studyMetadata;
        } else {
            return null;
        }
    } catch (final HibernateException e) {
        final String message = "Error with getStudyMetadataForGeolocationId() query from study with geoloCationId: "
                + geolocationId;
        DmsProjectDao.LOG.error(message, e);
        throw new MiddlewareQueryException(message, e);
    }
}

From source file:org.generationcp.middleware.dao.dms.DmsProjectDao.java

License:Open Source License

public List<MeasurementVariable> getObservationSetVariables(final List<Integer> observationSetIds,
        final List<Integer> variableTypes) {

    try {/*from ww  w. j  a  v  a 2 s .c  om*/
        final String query = " SELECT distinct " //
                + "   pp.variable_id AS " + OBS_SET_VARIABLE_ID + ", " //
                + "   variable.name AS " + OBS_SET_VARIABLE_NAME + ", " //
                + "   variable.definition AS " + OBS_SET_DESCRIPTION + ", " //
                + "   pp.alias AS " + OBS_SET_ALIAS + ", " //
                + "   pp.value as " + OBS_SET_VALUE + ", " + "   variableType.cvterm_id AS "
                + OBS_SET_VARIABLE_TYPE_ID + ", " //
                + "   scale.name AS " + OBS_SET_SCALE + ", " //
                + "   method.name AS " + OBS_SET_METHOD + ", " //
                + "   property.name AS " + OBS_SET_PROPERTY + ", " //
                + "   dataType.cvterm_id AS " + OBS_SET_DATA_TYPE_ID + ", " //
                + "   category.cvterm_id AS " + OBS_SET_CATEGORY_ID + ", " //
                + "   category.name AS " + OBS_SET_CATEGORY_NAME + ", " //
                + "   category.definition AS " + OBS_SET_CATEGORY_DESCRIPTION + ", " //
                + "   (SELECT formula_id FROM formula WHERE target_variable_id = pp.variable_id and active = 1 LIMIT 1) AS "
                + OBS_SET_FORMULA_ID + ", " + "   scaleMinRange.value AS " + OBS_SET_SCALE_MIN_RANGE + ", " //
                + "   scaleMaxRange.value AS " + OBS_SET_SCALE_MAX_RANGE + ", " //
                + "   vo.expected_min AS " + OBS_SET_EXPECTED_MIN + ", " //
                + "   vo.expected_max AS " + OBS_SET_EXPECTED_MAX + ", " //
                + "   cropOntology.value AS " + OBS_SET_CROP_ONTOLOGY_ID + "," + "   pp.value as "
                + OBS_SET_VARIABLE_VALUE + " FROM project dataset " //
                + "   INNER JOIN projectprop pp ON dataset.project_id = pp.project_id " //
                + "   INNER JOIN cvterm variable ON pp.variable_id = variable.cvterm_id " //
                + "   INNER JOIN cvterm variableType ON pp.type_id = variableType.cvterm_id " //
                + "   INNER JOIN cvterm_relationship cvtrscale ON variable.cvterm_id = cvtrscale.subject_id " //
                + "                                            AND cvtrscale.type_id = "
                + TermId.HAS_SCALE.getId() //
                + "   INNER JOIN cvterm scale ON cvtrscale.object_id = scale.cvterm_id " //
                + "   INNER JOIN cvterm_relationship cvtrmethod ON variable.cvterm_id = cvtrmethod.subject_id " //
                + "                                             AND cvtrmethod.type_id = "
                + TermId.HAS_METHOD.getId() //
                + "   INNER JOIN cvterm method ON cvtrmethod.object_id = method.cvterm_id " //
                + "   INNER JOIN cvterm_relationship cvtrproperty ON variable.cvterm_id = cvtrproperty.subject_id " //
                + "                                               AND cvtrproperty.type_id = "
                + TermId.HAS_PROPERTY.getId() //
                + "   INNER JOIN cvterm property ON cvtrproperty.object_id = property.cvterm_id " //
                + "   INNER JOIN cvterm_relationship cvtrdataType ON scale.cvterm_id = cvtrdataType.subject_id " //
                + "                                               AND cvtrdataType.type_id = "
                + TermId.HAS_TYPE.getId() //
                + "   INNER JOIN cvterm dataType ON cvtrdataType.object_id = dataType.cvterm_id " //
                + "   LEFT JOIN cvterm_relationship cvtrcategory ON scale.cvterm_id = cvtrcategory.subject_id "
                + "                                              AND cvtrcategory.type_id = "
                + TermId.HAS_VALUE.getId() //
                + "   LEFT JOIN cvterm category ON cvtrcategory.object_id = category.cvterm_id " //
                + "   LEFT JOIN cvtermprop scaleMaxRange on scale.cvterm_id = scaleMaxRange.cvterm_id " //
                + "                                         AND scaleMaxRange.type_id = "
                + TermId.MAX_VALUE.getId() //
                + "   LEFT JOIN cvtermprop scaleMinRange on scale.cvterm_id = scaleMinRange.cvterm_id " //
                + "                                         AND scaleMinRange.type_id = "
                + TermId.MIN_VALUE.getId() //
                + "   LEFT JOIN variable_overrides vo ON variable.cvterm_id = vo.cvterm_id " //
                + "                                      AND dataset.program_uuid = vo.program_uuid " //
                + "   LEFT JOIN cvtermprop cropOntology ON cropOntology.cvterm_id = variable.cvterm_id" //
                + "        AND cropOntology.type_id = " + TermId.CROP_ONTOLOGY_ID.getId() + " WHERE " //
                + "   dataset.project_id in (:observationSetIds) " //
                + "   AND pp.type_id in (:variableTypes) " + " ORDER BY pp.rank ";

        final SQLQuery sqlQuery = this.getSession().createSQLQuery(query);
        sqlQuery.setParameterList("observationSetIds", observationSetIds);
        sqlQuery.setParameterList("variableTypes", variableTypes);
        sqlQuery.addScalar(OBS_SET_VARIABLE_ID).addScalar(OBS_SET_VARIABLE_NAME).addScalar(OBS_SET_DESCRIPTION)
                .addScalar(OBS_SET_ALIAS).addScalar(OBS_SET_VALUE).addScalar(OBS_SET_VARIABLE_TYPE_ID)
                .addScalar(OBS_SET_SCALE).addScalar(OBS_SET_METHOD).addScalar(OBS_SET_PROPERTY)
                .addScalar(OBS_SET_DATA_TYPE_ID).addScalar(OBS_SET_CATEGORY_ID).addScalar(OBS_SET_CATEGORY_NAME)
                .addScalar(OBS_SET_CATEGORY_DESCRIPTION).addScalar(OBS_SET_SCALE_MIN_RANGE, new DoubleType())
                .addScalar(OBS_SET_SCALE_MAX_RANGE, new DoubleType())
                .addScalar(OBS_SET_EXPECTED_MIN, new DoubleType())
                .addScalar(OBS_SET_EXPECTED_MAX, new DoubleType())
                .addScalar(OBS_SET_FORMULA_ID, new IntegerType()).addScalar(OBS_SET_CROP_ONTOLOGY_ID)
                .addScalar(OBS_SET_VARIABLE_VALUE);

        sqlQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
        final List<Map<String, Object>> results = sqlQuery.list();

        final Map<Integer, MeasurementVariable> variables = new LinkedHashMap<>();

        for (final Map<String, Object> result : results) {
            final Integer variableId = (Integer) result.get("variableId");

            if (!variables.containsKey(variableId)) {
                variables.put(variableId, new MeasurementVariable());

                final MeasurementVariable measurementVariable = variables.get(variableId);

                measurementVariable.setTermId(variableId);
                measurementVariable.setName((String) result.get(OBS_SET_VARIABLE_NAME));
                measurementVariable.setAlias((String) result.get(OBS_SET_ALIAS));
                measurementVariable.setValue((String) result.get(OBS_SET_VALUE));
                measurementVariable.setDescription((String) result.get(OBS_SET_DESCRIPTION));
                measurementVariable.setScale((String) result.get(OBS_SET_SCALE));
                measurementVariable.setMethod((String) result.get(OBS_SET_METHOD));
                measurementVariable.setProperty((String) result.get(OBS_SET_PROPERTY));
                final VariableType variableType = VariableType
                        .getById((Integer) result.get(OBS_SET_VARIABLE_TYPE_ID));
                measurementVariable.setVariableType(variableType);
                //TODO: fix the saving of Treatment Factor Variables in the projectprop table.
                // Right now, the saved typeid is 1100. It should be 1809(VariableType.TREATMENT_FACTOR.getid())
                if (variableType != null) {
                    measurementVariable.setFactor(!variableType.getRole().equals(PhenotypicType.VARIATE));
                }
                final DataType dataType = DataType.getById((Integer) result.get(OBS_SET_DATA_TYPE_ID));
                measurementVariable.setDataType(dataType.getName());
                measurementVariable.setDataTypeId(dataType.getId());

                final Integer formulaId = (Integer) result.get(OBS_SET_FORMULA_ID);
                if (formulaId != null) {
                    final Formula formula = (Formula) this.getSession().createCriteria(Formula.class)
                            .add(Restrictions.eq("formulaId", formulaId)).add(Restrictions.eq("active", true))
                            .uniqueResult();
                    if (formula != null) {
                        measurementVariable.setFormula(FormulaUtils.convertToFormulaDto(formula));
                    }
                }

                final Double scaleMinRange = (Double) result.get(OBS_SET_SCALE_MIN_RANGE);
                final Double scaleMaxRange = (Double) result.get(OBS_SET_SCALE_MAX_RANGE);
                final Double expectedMin = (Double) result.get(OBS_SET_EXPECTED_MIN);
                final Double expectedMax = (Double) result.get(OBS_SET_EXPECTED_MAX);

                measurementVariable.setMinRange(expectedMin != null ? expectedMin : scaleMinRange);
                measurementVariable.setMaxRange(expectedMax != null ? expectedMax : scaleMaxRange);
                measurementVariable.setScaleMinRange(scaleMinRange);
                measurementVariable.setScaleMaxRange(scaleMaxRange);
                measurementVariable.setVariableMinRange(expectedMin);
                measurementVariable.setVariableMaxRange(expectedMax);
                measurementVariable.setCropOntology((String) result.get(OBS_SET_CROP_ONTOLOGY_ID));
            }

            final MeasurementVariable measurementVariable = variables.get(variableId);

            if (measurementVariable.getValue() == null || measurementVariable.getValue().isEmpty()) {
                measurementVariable.setValue((String) result.get(OBS_SET_VARIABLE_VALUE));
            }

            final Object categoryId = result.get(OBS_SET_CATEGORY_ID);
            if (categoryId != null) {
                if (measurementVariable.getPossibleValues() == null
                        || measurementVariable.getPossibleValues().isEmpty()) {
                    measurementVariable.setPossibleValues(new ArrayList<ValueReference>());
                }
                final ValueReference valueReference = //
                        new ValueReference((Integer) categoryId, //
                                Objects.toString(result.get(OBS_SET_CATEGORY_NAME)), //
                                Objects.toString(result.get(OBS_SET_CATEGORY_DESCRIPTION)));
                if (!measurementVariable.getPossibleValues().contains(valueReference)) {
                    measurementVariable.getPossibleValues().add(valueReference);
                }
            }
        }

        return new ArrayList<>(variables.values());
    } catch (final HibernateException e) {
        throw new MiddlewareQueryException(
                "Error getting datasets variables for dataset=" + observationSetIds + ": " + e.getMessage(), e);
    }
}