Example usage for org.hibernate Query getQueryString

List of usage examples for org.hibernate Query getQueryString

Introduction

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

Prototype

String getQueryString();

Source Link

Document

Get the query string.

Usage

From source file:org.chenillekit.hibernate.daos.AbstractHibernateDAO.java

License:Apache License

/**
 * retieve entites by HQL query./*from  w ww .  j a  va 2  s .  com*/
 *
 * @param queryString the query to fin entities.
 * @param offset      record number where start to read.
 * @param limit       amount of records to read.
 * @param parameters  the (optional) parameters for the query.
 *
 * @return list of entities
 */
@SuppressWarnings("unchecked")
public List<T> findByQuery(String queryString, int offset, int limit, Collection<QueryParameter> parameters) {
    Query query = session.createQuery(queryString);
    for (QueryParameter parameter : parameters) {
        if (parameter.getParameterValue() instanceof Collection)
            query.setParameterList(parameter.getParameterName(), (Collection) parameter.getParameterValue());
        else
            query.setParameter(parameter.getParameterName(), parameter.getParameterValue());
    }

    if (limit > 0)
        query.setMaxResults(limit);

    if (offset > 0)
        query.setFirstResult(offset);

    if (logger.isDebugEnabled())
        logger.debug(query.getQueryString());

    return query.list();
}

From source file:org.chenillekit.hibernate.daos.AbstractHibernateDAO.java

License:Apache License

/**
 * bulk database record update.//from  ww w . j ava 2 s. c  o m
 *
 * @param queryString the query to update records.
 * @param parameters  the (optional) parameters for the query.
 *
 * @return quantity of updated records
 */
public int updateByQuery(String queryString, QueryParameter... parameters) {
    Query query = session.createQuery(queryString);
    for (QueryParameter parameter : parameters) {
        if (parameter.getParameterValue() instanceof Collection)
            query.setParameterList(parameter.getParameterName(), (Collection) parameter.getParameterValue());
        else
            query.setParameter(parameter.getParameterName(), parameter.getParameterValue());
    }

    if (logger.isDebugEnabled())
        logger.debug(query.getQueryString());

    return query.executeUpdate();
}

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

License:Apache License

/**
 * {@inheritDoc}//from   w w w .  j  ava 2s. co  m
 */
public Query generate(QueryMethodParameterInfo qmpi, HibernateQueryExecutionContext context) {
    Query query = createQuery(qmpi, context);
    logger.debug("Using query: {}", query.getQueryString().trim());
    applyQuerySettings(qmpi, context, query);
    return query;
}

From source file:org.egov.egf.web.actions.report.ChequeIssueRegisterReportAction.java

License:Open Source License

public void generateReport() throws JRException, IOException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("----Inside generateReport---- ");

    accountNumber = (Bankaccount) persistenceService.find("from Bankaccount where id=?", accountNumber.getId());
    if (accountNumber.getChequeformat() != null && !accountNumber.getChequeformat().equals("")) {
        chequeFormat = accountNumber.getChequeformat().getId().toString();
    }/*from ww w .  jav  a 2s  .  co  m*/

    validateDates(fromDate, toDate);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Querying to date range " + getFormattedDate(fromDate) + "to date "
                + getFormattedDate(getNextDate(toDate)));
    // persistenceService.setType(InstrumentHeader.class);
    final List<AppConfigValues> printAvailConfig = appConfigValuesService
            .getConfigValuesByModuleAndKey(FinancialConstants.MODULE_NAME_APPCONFIG, "chequeprintavailableat");

    chequePrintingEnabled = isChequePrintEnabled();

    for (final AppConfigValues appConfigVal : printAvailConfig)
        chequePrintAvailableAt = appConfigVal.getValue();

    final Query query = persistenceService.getSession()
            .createSQLQuery("select ih.instrumentnumber as chequeNumber,ih.instrumentdate as chequeDate,"
                    + "ih.instrumentamount as chequeAmount,vh.vouchernumber as voucherNumber,vh.id as vhId,ih.serialno as serialNo,vh.voucherdate as voucherDate,vh.name as voucherName,ih.payto as payTo,mbd.billnumber as billNumber,"
                    + "mbd.billDate as billDate,vh.type as type,es.DESCRIPTION as chequeStatus,ih.id as instrumentheaderid from egf_instrumentHeader ih,egf_instrumentvoucher iv,EGW_STATUS es,"
                    + "voucherheader vh left outer join miscbilldetail mbd on  vh.id=mbd.PAYVHID ,vouchermis vmis where ih.instrumentDate <'"
                    + getFormattedDate(getNextDate(toDate)) + "' and ih.instrumentDate>='"
                    + getFormattedDate(fromDate) + "' and ih.isPayCheque='1' "
                    + "and ih.INSTRUMENTTYPE=(select id from egf_instrumenttype where TYPE='cheque' ) and vh.status not in ("
                    + getExcludeVoucherStatues() + ") and vh.id=iv.voucherheaderid and  bankAccountId="
                    + accountNumber.getId() + " and ih.id=iv.instrumentheaderid and ih.id_status=es.id "
                    + " and vmis.voucherheaderid=vh.id " + createQuery()
                    + " order by ih.instrumentDate,ih.instrumentNumber ")
            .addScalar("chequeNumber").addScalar("chequeDate", StandardBasicTypes.DATE)
            .addScalar("chequeAmount", BigDecimalType.INSTANCE).addScalar("voucherNumber")
            .addScalar("voucherDate", StandardBasicTypes.DATE).addScalar("voucherName").addScalar("payTo")
            .addScalar("billNumber").addScalar("billDate", StandardBasicTypes.DATE).addScalar("type")
            .addScalar("vhId", BigDecimalType.INSTANCE).addScalar("serialNo", LongType.INSTANCE)
            .addScalar("chequeStatus").addScalar("instrumentHeaderId", LongType.INSTANCE)
            .setResultTransformer(Transformers.aliasToBean(ChequeIssueRegisterDisplay.class));
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Search query" + query.getQueryString());
    chequeIssueRegisterList = query.list();
    if (chequeIssueRegisterList == null)
        chequeIssueRegisterList = new ArrayList<ChequeIssueRegisterDisplay>();
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Got Cheque list| Size of list is" + chequeIssueRegisterList.size());
    updateBillNumber();
    updateVoucherNumber();
    removeDuplicates();
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("--End  generateReport--");
}

From source file:org.egov.pims.dao.PersonalInformationHibernateDAO.java

License:Open Source License

/**
  * Returning temporary  assigned employee object by pepartment,designation,functionary,date 
  * @param deptId/*from  w w w . j a  v a 2  s  .c om*/
  * @param DesigId
  * @param functionaryId
  * @param onDate
  * @return Employee
  * @throws Exception 
  */
public PersonalInformation getTempAssignedEmployeeByDeptDesigFunctionaryDate(Integer deptId, Integer desigId,
        Integer functionaryId, Date onDate) throws Exception {
    PersonalInformation tempAssignedEemployee = null;
    LOGGER.info("Inside temp assigned emp API-----------");
    List<PersonalInformation> listEmployee = null;
    Query qry = getCurrentSession()
            .createQuery("select A.employee from Assignment A where " + "A.deptId.id=:deptId and "
                    + "A.desigId.designationId=:desigId and " + "A.functionary.id=:functionaryId and "
                    + "A.isPrimary = 'N' and " + "((A.toDate IS NULL and A.fromDate <= :onDate) OR "
                    + "(A.fromDate <= :onDate and A.toDate >= :onDate))");
    qry.setInteger("deptId", deptId);
    qry.setInteger("desigId", desigId);
    qry.setInteger("functionaryId", functionaryId);
    qry.setDate("onDate", onDate);
    LOGGER.info("Inside temp assigned emp API query-----------" + qry.getQueryString());
    listEmployee = qry.list();
    if (listEmployee.size() == 0) {
        throw new NoSuchObjectException("tempAssigned.personalinformation.object.notFound");
    }
    if (listEmployee.size() > 1) {
        throw new TooManyValuesException("tempAssigned.personalinformation.object.Foundmorethanone");
    }
    if (listEmployee.size() == 1) {
        tempAssignedEemployee = listEmployee.get(0);
    }
    return tempAssignedEemployee;
}

From source file:org.egov.pims.dao.PersonalInformationHibernateDAO.java

License:Open Source License

public List getAllDesignationByDept(Integer deptId) throws TooManyValuesException, NoSuchObjectException {
    List<Designation> desgMstr = null;
    try {/*from w w w  .j av a  2  s . com*/

        Query qry = getCurrentSession().createQuery("from Designation dm where dm.deptId =:deptId");
        qry.setInteger("deptId", deptId);
        LOGGER.info("QUERY TEST-----------" + qry.getQueryString());
        desgMstr = qry.list();

    } catch (Exception e) {

        throw new ApplicationRuntimeException("system.error", e);
    }

    return desgMstr;
}

From source file:org.egov.pims.service.EmployeeServiceImpl.java

License:Open Source License

/**
 * Returns a list of assignment ids. All assignments for the employee based
 * on employee id and that fall in the given date will be returned.
 * /*  w w  w  . ja  va2s  .  c  o m*/
 * @param empId
 *            - Required parameter. If null is passed, the API throws an
 *            ApplicationException
 * @param givenDate
 *            . Date as on which the assignments need to be returned. If
 *            this parameter is null, the current date is considered
 * @return List of Assignment Ids
 * @throws ApplicationException
 */
public List<Integer> getAssignmentsForEmp(Integer empId, Date givenDate) throws ApplicationException {
    List list = null;
    Query query = null;
    try {

        StringBuffer stringbuffer = new StringBuffer(
                " select    ASS_ID  from EG_EIS_EMPLOYEEINFO ev  where ev.ID = :empId");

        if (empId == null) {
            throw new ApplicationException("EmployeeId  Not provided");
        } else if (givenDate == null) {
            stringbuffer.append(
                    " and ((ev.to_Date is null and ev.from_Date <= SYSDATE ) OR (ev.from_Date <= SYSDATE AND ev.to_Date >= SYSDATE))");

        } else {
            stringbuffer.append(" and  ev.from_Date <= :givenDate AND ev.to_Date >= :givenDate");
        }
        query = getCurrentSession().createSQLQuery(stringbuffer.toString()).addScalar("ASS_ID",
                IntegerType.INSTANCE);

        if (query.getQueryString().contains(":givenDate")) {
            query.setDate("givenDate", givenDate);
        }

        query.setInteger("empId", empId);

    } catch (HibernateException hibException) {
        LOGGER.error(hibException.getMessage());
        throw new ApplicationException("HibernateException:" + hibException.getMessage(), hibException);
    }

    return query.list();

}

From source file:org.esupportail.commons.dao.AbstractHibernateQueryPaginator.java

License:Apache License

/**
 * @see org.esupportail.commons.web.beans.AbstractPaginator#loadItemsInternal()
 *//*  w w  w .  ja v a 2  s  . c  o m*/
@Override
@SuppressWarnings("unchecked")
protected void loadItemsInternal() {
    String queryString = getQueryString();
    if (queryString == null) {
        setVisibleItems(new ArrayList<E>());
        setCurrentPageInternal(0);
        setTotalItemsCount(0);
        return;
    }
    Query query = getDaoService().getQuery(queryString);
    ScrollableResults scrollableResults = query.scroll();
    /* 
     * We set the max results to one more than the specfied pageSize to 
     * determine if any more results exist (i.e. if there is a next page 
     * to display). The result set is trimmed down to just the pageSize 
     * before being displayed later (in getList()). 
     */
    if (logger.isDebugEnabled()) {
        logger.debug("executing " + query.getQueryString() + "...");
    }
    query.setFirstResult(getCurrentPageInternal() * getPageSize());
    query.setMaxResults(getPageSize());
    setVisibleItems(query.list());
    // the total number of results is computed here since scrolling is not allowed when rendering
    scrollableResults.last();
    setTotalItemsCount(scrollableResults.getRowNumber() + 1);
    if (logger.isDebugEnabled()) {
        logger.debug("done.");
    }
    if (getVisibleItemsCountInternal() == 0 && getTotalItemsCountInternal() != 0) {
        setCurrentPageInternal(getLastPageNumberInternal());
        loadItemsInternal();
    }
    updateLoadTime();
}

From source file:org.genedb.querying.core.HqlQuery.java

License:Open Source License

@Override
public List<String> getResults() throws QueryException {

    Session session = SessionFactoryUtils.doGetSession(sessionFactory, false);

    Map<String, String> map = new HashMap<String, String>();
    map.put("ORGANISM", getOrganismHql());
    map.put("SELECTOR", featureSelector);
    map.put("ORDERBY", getOrderBy());

    String hql = restrictQuery(getHql(), map);

    org.hibernate.Query query = session.createQuery(hql);
    populateQueryWithParams(query);//ww  w .  ja  v  a 2s  .  c  o m

    logger.debug(query.getQueryString());

    //Run query
    List<String> ret = query.setMaxResults(maxResults).list();

    //Get the result size
    if (ret != null && getMaxResults() == ret.size()) {
        isActualResultSizeSameAsMax = true;
    }

    return ret;

}

From source file:org.genedb.querying.core.HqlQuery.java

License:Open Source License

@Override
public List<String> getResults(int start, int end) throws QueryException {

    Session session = SessionFactoryUtils.doGetSession(sessionFactory, false);

    Map<String, String> map = new HashMap<String, String>();
    map.put("ORGANISM", getOrganismHql());
    map.put("SELECTOR", featureSelector);
    map.put("ORDERBY", getOrderBy());

    String hql = restrictQuery(getHql(), map);

    org.hibernate.Query query = session.createQuery(hql);
    populateQueryWithParams(query);// ww  w.jav a2s.c o  m

    logger.debug(query.getQueryString());

    //int start = page * length;

    logger.info(getQueryName() + " getResults() paging " + start + "-" + end);

    //Run query
    @SuppressWarnings("unchecked")
    List<String> ret = query.setFirstResult(start).setMaxResults(end - start + 1).list();

    //Get the result size
    if (ret != null && getMaxResults() == ret.size()) {
        isActualResultSizeSameAsMax = true;
    }

    return ret;

}