Example usage for org.hibernate Query setDate

List of usage examples for org.hibernate Query setDate

Introduction

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

Prototype

@Deprecated
@SuppressWarnings("unchecked")
default Query<R> setDate(String name, Date val) 

Source Link

Document

Bind the val (time is truncated) of a given Date object to a named query parameter.

Usage

From source file:mx.gob.cfe.documentos.dao.SobreDao.java

public List<Sobre> reporteSabado(Date fecha) {
    Query query = currentSession().createQuery("select s from Sobre s  where s.fecha=:fecha ");
    query.setDate("fecha", fecha);
    return query.list();
}

From source file:net.big_oh.resourcestats.dao.RequestorDAO.java

License:Open Source License

public LinkedHashMap<Requestor, Number> getMostFrequentRequestors(int maxNumRequestors, Date since)
        throws IllegalArgumentException {
    // translate null parameters
    if (since == null) {
        // set an appropriate default value
        since = new Date(0);
    }/*from w ww  .j av  a2s . c  om*/

    // sanity check for parameters
    if (maxNumRequestors < 1) {
        throw new IllegalArgumentException("Argument maxNumRequestors must not be less than 1.");
    }
    if (since.after(new Date())) {
        throw new IllegalArgumentException("Argument since must not be after the current system time.");
    }

    Query query = getQualifiedNamedQuery("getMostFrequentRequestors");
    query.setMaxResults(maxNumRequestors);
    query.setDate("since", since);

    return processQueryResults(query.list());
}

From source file:net.big_oh.resourcestats.dao.ResourceDAO.java

License:Open Source License

public LinkedHashMap<Resource, Number> getMostPopularResources(int maxNumResources, Date since)
        throws IllegalArgumentException {
    // translate null parameters
    if (since == null) {
        // set an appropriate default value
        since = new Date(0);
    }/* w w w.  j a  v  a  2s  .  com*/

    // sanity check for parameters
    if (maxNumResources < 1) {
        throw new IllegalArgumentException("Argument maxNumResources must not be less than 1.");
    }
    if (since.after(new Date())) {
        throw new IllegalArgumentException("Argument since must not be after the current system time.");
    }

    Query query = getQualifiedNamedQuery("getMostPopularResources");
    query.setMaxResults(maxNumResources);
    query.setDate("since", since);

    return processQueryResults(query.list());
}

From source file:net.mlw.vlh.adapter.hibernate3.util.setter.DateSetter.java

License:Open Source License

/**
 * <ol>//w  ww  .java2  s.  c  om
 * <li>If is value instance of the String, it try to parse value using
 * SimpleDateFormat with specified format.</li>
 * <li>If is value instance of the Date, it will set it directly to query .
 * </li>
 * <li>Otherwise it will set null to query for key.</li>
 * </ol>
 * 
 * @see net.mlw.vlh.adapter.hibernate3.util.Setter#set(org.hibernate.Query,
 *      java.lang.String, java.lang.Object)
 * @see #setFormat(String)
 */
public void set(Query query, String key, Object value) throws HibernateException, ParseException {
    Date date = null;
    if (value instanceof String) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("The key='" + key + "'s value is instance of a String, now is parsing to date.");
        }
        date = formatter.parse((String) value);
    } else if (value instanceof Date) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("The key='" + key + "' is instance of a Date.");
        }
        date = (Date) value;
    } else if (value == null) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("The key='" + key + "'s value is null.");
        }
    } else {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("The key's='" + key + "' value='" + value
                    + "' was expected as Date or String parseable to Date.");
        }
        throw new IllegalArgumentException(
                "Cannot convert value of class " + value.getClass().getName() + " to date (key=" + key + ")");
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("The key='" + key + "' was set to the query as Date with the date='" + date + "'.");
    }

    query.setDate(key, date);
}

From source file:org.caisi.dao.TicklerDAO.java

License:Open Source License

public int getActiveTicklerCount(String providerNo) {
    ArrayList paramList = new ArrayList();
    //String query = "select count(*) from Tickler t where t.status = 'A' and t.service_date <= ? and (t.task_assigned_to  = '"+ providerNo + "' or t.task_assigned_to='All Providers')";

    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.setTime(new Date());
    /*paramList.add(currentDate.getTime());
    //paramList.add(new Date());/*from  ww  w  .  j a  v  a  2 s . c  o  m*/
    Object params[] = paramList.toArray(new Object[paramList.size()]);
    Long count = (Long) getHibernateTemplate().find(query ,params).get(0);*/

    String query = "select count(*) from tickler t where t.status = 'A' and t.service_date <= ? and (t.task_assigned_to  = '"
            + providerNo + "' or t.task_assigned_to='All Providers')";
    if (org.oscarehr.common.IsPropertiesOn.isMultisitesEnable()) {
        SuperSiteUtil superSiteUtil = SuperSiteUtil.getInstance(providerNo);
        List<Site> sites = superSiteUtil.getSitesWhichUserCanOnlyAccess();
        String siteStr = "";
        if (sites != null && sites.size() > 0) {
            for (Site site : sites) {
                if (siteStr.length() == 0)
                    siteStr = "'" + site.getId() + "'";
                else
                    siteStr = siteStr + ",'" + site.getId() + "'";
            }
            //get tickler which are not assigned to any demographic or which are assigned to demographic
            //enrolled in sites in which provider has only access 
            query = "select count(*) from tickler t "
                    + " left join demographicSite ds on t.demographic_no=ds.demographicId "
                    + " where t.status = 'A' " + " and t.service_date <= ? and  " + " (t.task_assigned_to  = '"
                    + providerNo + "' or t.task_assigned_to='All Providers') "
                    + " and (t.demographic_no is null or t.demographic_no = '' or ds.siteId in (" + siteStr
                    + "))";
        }
    }

    Query hibernateQuery = getSession().createSQLQuery(query);
    hibernateQuery.setDate(0, currentDate.getTime());
    List resultList = hibernateQuery.list();

    int count = 0;

    if (resultList != null && resultList.size() > 0)
        count = Integer.parseInt(resultList.get(0) + "");
    //return count.intValue();
    return count;
}

From source file:org.dspace.checker.dao.impl.ChecksumHistoryDAOImplTest.java

License:BSD License

/**
 * Test of deleteByDateAndCode method, of class ChecksumHistoryDAOImpl.
 *///from  w  ww . ja v  a  2 s .c om
@Test
public void testDeleteByDateAndCode() throws Exception {
    System.out.println("deleteByDateAndCode");

    GregorianCalendar cal = new GregorianCalendar();
    Date retentionDate = cal.getTime();
    ChecksumResultCode resultCode = ChecksumResultCode.CHECKSUM_MATCH;

    // Create two older rows
    HibernateDBConnection dbc = (HibernateDBConnection) CoreHelpers.getDBConnection(context);
    Query qry = dbc.getSession().createSQLQuery(
            "INSERT INTO checksum_history" + "(check_id, process_end_date, result, bitstream_id)"
                    + " VALUES (:id, :date, :result, :bitstream)");
    int checkId = 0;

    // Row with matching result code
    BitstreamService bss = ContentServiceFactory.getInstance().getBitstreamService();
    InputStream is = new ByteArrayInputStream(new byte[0]);
    Bitstream bs = bss.create(context, is);
    context.turnOffAuthorisationSystem();
    bss.update(context, bs);
    context.restoreAuthSystemState();

    cal.roll(Calendar.DATE, -1);
    Date matchDate = cal.getTime();
    checkId++;
    qry.setInteger("id", checkId);
    qry.setDate("date", matchDate);
    qry.setString("result", ChecksumResultCode.CHECKSUM_MATCH.name());
    qry.setString("bitstream", bs.getID().toString()); // FIXME identifier not being set???
    qry.executeUpdate();

    // Row with nonmatching result code
    cal.roll(Calendar.DATE, -1);
    Date noMatchDate = cal.getTime();
    checkId++;
    qry.setInteger("id", checkId);
    qry.setDate("date", noMatchDate);
    qry.setString("result", ChecksumResultCode.CHECKSUM_NO_MATCH.name());
    qry.setString("bitstream", bs.getID().toString());
    qry.executeUpdate();

    // Create one newer row
    cal.roll(Calendar.DATE, +3);
    Date futureDate = cal.getTime();
    checkId++;
    qry.setInteger("id", checkId);
    qry.setDate("date", new java.sql.Date(futureDate.getTime()));
    qry.setString("result", ChecksumResultCode.CHECKSUM_MATCH.name());
    qry.setString("bitstream", bs.getID().toString());
    qry.executeUpdate();

    // Test!
    ChecksumHistoryDAOImpl instance = new ChecksumHistoryDAOImpl();
    int expResult = 1;
    int result = instance.deleteByDateAndCode(context, retentionDate, resultCode);
    assertEquals(expResult, result);

    // See if matching old row is gone.
    qry = dbc.getSession().createQuery("SELECT COUNT(*) FROM ChecksumHistory WHERE process_end_date = :date");
    long count;

    qry.setDate("date", matchDate);
    count = (Long) qry.uniqueResult();
    assertEquals("Should find no row at matchDate", count, 0);

    // See if nonmatching old row is still present.
    qry.setDate("date", noMatchDate);
    count = (Long) qry.uniqueResult();
    assertEquals("Should find one row at noMatchDate", count, 1);

    // See if new row is still present.
    qry.setDate("date", futureDate);
    count = (Long) qry.uniqueResult();
    assertEquals("Should find one row at futureDate", count, 1);
}

From source file:org.egov.collection.integration.services.CollectionIntegrationServiceImpl.java

License:Open Source License

@Override
public List<RestAggregatePaymentInfo> getAggregateReceiptTotal(final PaymentInfoSearchRequest aggrReq) {

    final List<RestAggregatePaymentInfo> listAggregatePaymentInfo = new ArrayList<>(0);
    final StringBuilder queryBuilder = new StringBuilder(
            "select  sum(recordcount) as records,ulb, sum(total) as total,service  from ")
                    .append(environmentSettings.statewideSchemaName())
                    .append(".receipt_aggr_view "
                            + " where receipt_date>=:fromDate and receipt_date<=:toDate and service=:serviceCode "
                            + " and source=:source and ulb=:ulbCode  group by ulb,service  ");

    final Query query = getSession().createSQLQuery(queryBuilder.toString());
    query.setDate("fromDate", aggrReq.getFromdate());
    query.setDate("toDate", aggrReq.getTodate());
    query.setString("serviceCode", aggrReq.getServicecode());
    query.setString("source", aggrReq.getSource());
    query.setString("ulbCode", aggrReq.getUlbCode());

    LOGGER.debug(aggrReq.getSource());/*  www  .  j a v  a  2s.c  om*/

    final List<Object[]> queryResults = query.list();

    for (final Object[] objectArray : queryResults) {
        final RestAggregatePaymentInfo aggregatePaymentInfo = new RestAggregatePaymentInfo();
        aggregatePaymentInfo.setTxncount(Integer.parseInt(objectArray[0].toString()));
        aggregatePaymentInfo.setUlbcode(objectArray[1].toString());
        aggregatePaymentInfo.setTxnamount(new BigDecimal(objectArray[2].toString()));
        aggregatePaymentInfo.setServiceCode(objectArray[3].toString());
        listAggregatePaymentInfo.add(aggregatePaymentInfo);
    }
    if (listAggregatePaymentInfo.isEmpty())
        listAggregatePaymentInfo.add(new RestAggregatePaymentInfo());
    return listAggregatePaymentInfo;
}

From source file:org.egov.collection.service.ReceiptHeaderService.java

License:Open Source License

/**
 * @param statusCode Status code of receipts to be fetched. If null or ALL, then receipts with all statuses are fetched
 * @param userName User name of the user who has created the receipts. If null or ALL, then receipts of all users are fetched
 * @param counterId Counter id on which the receipts were created. If negative, then receipts from all counters are fetched
 * @param serviceCode Service code for which the receipts were created. If null or ALL, then receipts of all billing services
 * are fetched//from  ww w. j  av  a  2 s .com
 * @return List of all receipts created by given user from given counter id and having given status
 */
public List<ReceiptHeader> findAllByPositionAndInboxItemDetails(final List<Long> positionIds,
        final String groupingCriteria) {
    final StringBuilder query = new StringBuilder(
            " select distinct (receipt) from org.egov.collection.entity.ReceiptHeader receipt ");
    String wfAction = null;
    String serviceCode = null;
    String userName = null;
    String receiptDate = null;
    String receiptType = null;
    Integer counterId = null;
    String paymentMode = null;
    final String params[] = groupingCriteria.split(CollectionConstants.SEPARATOR_HYPHEN, -1);
    if (params.length == 7) {
        wfAction = params[0];
        serviceCode = params[1];
        userName = params[2];
        counterId = Integer.valueOf(params[4]);
        receiptDate = params[3];
        receiptType = params[5];
        paymentMode = params[6];
    }
    final boolean allCounters = counterId == null || counterId < 0;
    // final boolean allPositions = positionIds == null ||
    // positionIds.equals(CollectionConstants.ALL);
    final boolean allServices = serviceCode == null || serviceCode.equals(CollectionConstants.ALL);
    final boolean allWfAction = wfAction == null || wfAction.equals(CollectionConstants.ALL);
    final boolean allUserName = userName == null || userName.equals(CollectionConstants.ALL);
    final boolean allDate = receiptDate == null || receiptDate.equals(CollectionConstants.ALL);
    final SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    Date rcptDate = null;
    try {
        rcptDate = formatter.parse(receiptDate);
    } catch (final ParseException e) {
        LOGGER.error("Exception while parsing ReceiptDate", e);
        throw new ApplicationRuntimeException(e.getMessage());
    }

    if (paymentMode.equals(CollectionConstants.INSTRUMENTTYPE_CASH)
            || paymentMode.equals(CollectionConstants.INSTRUMENTTYPE_CHEQUEORDD))
        query.append("join receipt.receiptInstrument as instruments ");

    query.append(" where 1=1 and receipt.state.value != 'END' and receipt.state.status != 2 ");
    // if (!allPositions)
    query.append(" and receipt.state.ownerPosition.id in :positionIds");
    if (!allCounters)
        query.append(" and receipt.location.id = :counterId");
    if (!allServices && receiptType.equals(CollectionConstants.SERVICE_TYPE_BILLING))
        query.append(" and receipt.service.code = :serviceCode");
    if (!allWfAction)
        query.append(" and receipt.state.nextAction = :wfAction");
    if (!allUserName)
        query.append(" and receipt.createdBy.username = :userName");
    if (!allDate)
        query.append(" and (cast(receipt.receiptdate as date)) = :rcptDate");
    if (receiptType.equals(CollectionConstants.SERVICE_TYPE_BILLING))
        query.append(" and receipt.receipttype = :receiptType");
    else
        query.append(" and receipt.receipttype in ('A', 'C')");

    if (paymentMode.equals(CollectionConstants.INSTRUMENTTYPE_CASH)
            || paymentMode.equals(CollectionConstants.INSTRUMENTTYPE_CHEQUEORDD))
        query.append(" and instruments.instrumentType.type in (:paymentMode )");
    query.append(" order by receipt.receiptdate  desc");
    final Query listQuery = getSession().createQuery(query.toString());

    // if (!allPositions)
    listQuery.setParameterList("positionIds", positionIds);
    if (!allCounters)
        listQuery.setInteger("counterId", counterId);
    if (!allServices && receiptType.equals(CollectionConstants.SERVICE_TYPE_BILLING))
        listQuery.setString("serviceCode", serviceCode);
    if (!allWfAction)
        listQuery.setString("wfAction", wfAction);
    if (!allUserName)
        listQuery.setString("userName", userName);
    if (!allDate)
        listQuery.setDate("rcptDate", rcptDate);
    if (receiptType.equals(CollectionConstants.SERVICE_TYPE_BILLING))
        listQuery.setCharacter("receiptType", receiptType.charAt(0));
    if (paymentMode.equals(CollectionConstants.INSTRUMENTTYPE_CASH))
        listQuery.setString("paymentMode", paymentMode);
    else if (paymentMode.equals(CollectionConstants.INSTRUMENTTYPE_CHEQUEORDD))
        listQuery.setParameterList("paymentMode", new ArrayList<>(Arrays.asList("cheque", "dd")));
    return listQuery.list();
}

From source file:org.egov.commons.dao.FinancialYearHibernateDAO.java

License:Open Source License

/**
 * @param fromDate// w  w  w .  ja  va 2 s.c o m
 * @param toDate
 *            will will return false if any financialyear is not active for
 *            posting within given date range
 */
public boolean isFinancialYearActiveForPosting(Date fromDate, Date toDate) {

    logger.info("Obtained session");
    String result = "";
    Query query = getCurrentSession().createQuery(""
            + " from CFinancialYear cfinancialyear where   cfinancialyear.isActiveForPosting=false and cfinancialyear.startingDate <=:sDate and cfinancialyear.endingDate >=:eDate  ");
    query.setDate("sDate", fromDate);
    query.setDate("eDate", toDate);
    ArrayList list = (ArrayList) query.list();
    if (list.size() > 0)
        return false;
    else
        return true;

}

From source file:org.egov.commons.dao.FinancialYearHibernateDAO.java

License:Open Source License

/**
 * gives active FY only else throws//w w  w  .j  av a  2 s  .  c o  m
 * ApplicationRuntimeException("Financial Year is not active For Posting.")
 */

public CFinancialYear getFinancialYearByDate(Date date) {
    CFinancialYear cFinancialYear = null;
    logger.info("Obtained session");
    String result = "";
    Query query = getCurrentSession().createQuery(
            " from CFinancialYear cfinancialyear where cfinancialyear.startingDate <=:sDate and cfinancialyear.endingDate >=:eDate  and cfinancialyear.isActiveForPosting=true");
    query.setDate("sDate", date);
    query.setDate("eDate", date);
    ArrayList list = (ArrayList) query.list();
    if (list.size() > 0)
        cFinancialYear = (CFinancialYear) list.get(0);
    if (null == cFinancialYear)
        throw new ApplicationRuntimeException("Financial Year is not active For Posting.");
    return cFinancialYear;
}