Example usage for org.hibernate Query setTimestamp

List of usage examples for org.hibernate Query setTimestamp

Introduction

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

Prototype

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

Source Link

Document

Bind the value and the time of a given Date object to a named query parameter.

Usage

From source file:org.celllife.idart.gui.reportParameters.CohortDrugCollections.java

License:Open Source License

private EntitySet getPatientSet(ExcelReportObject report) {
    String patientQuery = "select e.patient.id from Episode e where e.startDate between :startDate and :endDate"
            + " and e.startReason = :startReason";
    Query query = getHSession().createQuery(patientQuery);
    query.setString("startReason", Episode.REASON_NEW_PATIENT);
    query.setTimestamp("startDate", report.getStartDate());
    query.setTimestamp("endDate", report.getEndDate());
    @SuppressWarnings("unchecked")
    List<Integer> patients = query.list();
    return new EntitySet(patients);
}

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

License:BSD License

@Override
public int deleteByDateAndCode(Context context, Date retentionDate, ChecksumResultCode resultCode)
        throws SQLException {
    String hql = "delete from ChecksumHistory where processEndDate < :processEndDate AND checksumResult.resultCode=:resultCode";
    Query query = createQuery(context, hql);
    query.setTimestamp("processEndDate", retentionDate);
    query.setParameter("resultCode", resultCode);
    return query.executeUpdate();
}

From source file:org.dspace.content.dao.impl.ItemDAOImpl.java

License:BSD License

@Override
public Iterator<Item> findAll(Context context, boolean archived, boolean withdrawn, boolean discoverable,
        Date lastModified) throws SQLException {
    StringBuilder queryStr = new StringBuilder();
    queryStr.append("SELECT i FROM Item i");
    queryStr.append(" WHERE (inArchive = :in_archive OR withdrawn = :withdrawn)");
    queryStr.append(" AND discoverable = :discoverable");

    if (lastModified != null) {
        queryStr.append(" AND last_modified > :last_modified");
    }//from   w w  w .j  a  v  a2s. c o m

    Query query = createQuery(context, queryStr.toString());
    query.setParameter("in_archive", archived);
    query.setParameter("withdrawn", withdrawn);
    query.setParameter("discoverable", discoverable);
    if (lastModified != null) {
        query.setTimestamp("last_modified", lastModified);
    }
    return iterate(query);
}

From source file:org.dspace.content.dao.impl.ItemDAOImpl.java

License:BSD License

@Override
public Iterator<Item> findByLastModifiedSince(Context context, Date since) throws SQLException {
    Query query = createQuery(context, "SELECT i FROM item i WHERE last_modified > :last_modified");
    query.setTimestamp("last_modified", since);
    return iterate(query);
}

From source file:org.egov.dao.budget.BudgetDetailsHibernateDAO.java

License:Open Source License

/**
 * @description - get the list of BudgetUsage based on various parameters
 * @param queryParamMap// w  ww  . j a  va 2s  . c  o  m
 *            - HashMap<String, Object> queryParamMap will have data
 *            required for the query the queryParamMap contain values :- the
 *            mis attribute values passed in the query map will be validated
 *            with the appconfig value of key=budgetaryCheck_groupby_values
 *            financialyearid - optional ExecutionDepartmentId - mandatory
 *            -if:department present in the app config value - optional
 *            -else fundId - mandatory -if:fund present in the app config
 *            value - optional -else schemeId - mandatory -if:Scheme present
 *            in the app config value - optional -else functionId -
 *            mandatory -if:function present in the app config value -
 *            optional -else subschemeId - mandatory -if:Subscheme present
 *            in the app config value - optional -else functionaryId -
 *            mandatory -if:functionary present in the app config value -
 *            optional -else boundaryId - mandatory -if:boundary present in
 *            the app config value - optional -else moduleId - optional
 *            financialYearId -optional budgetgroupId -optional fromDate
 *            -optional toDate -optional Order By - optional if passed then
 *            only Budgetary appropriation number and reference number is
 *            accepted, if not passed then default order by is date.
 * @return
 */

@Override
@SuppressWarnings("unchecked")
public List<BudgetUsage> getListBudgetUsage(final Map<String, Object> queryParamMap) {

    final StringBuffer query = new StringBuffer();
    final Map<String, String> grpByVls = new HashMap<String, String>();
    List<BudgetUsage> listBudgetUsage = null;
    query.append("select bu from BudgetUsage bu,BudgetDetail bd where  bu.budgetDetail.id=bd.id");
    final List<AppConfigValues> list = appConfigValuesService.getConfigValuesByModuleAndKey(EGF,
            BUDGETARY_CHECK_GROUPBY_VALUES);
    if (list.isEmpty())
        throw new ValidationException(EMPTY_STRING,
                "budgetaryCheck_groupby_values is not defined in AppConfig");
    final AppConfigValues appConfigValues = list.get(0);
    if (appConfigValues.getValue().indexOf(",") != 1) { // if there are more
        // than one comma
        // separated values
        // for key =
        // budgetaryCheck_groupby_values
        final String[] values = StringUtils.split(appConfigValues.getValue(), ",");
        for (final String value : values)
            grpByVls.put(value, value);
    } else
        grpByVls.put(appConfigValues.getValue(), appConfigValues.getValue());

    if (!isNull(grpByVls.get("fund")))
        if (isNull(queryParamMap.get("fundId")))
            throw new ValidationException(EMPTY_STRING, "Fund is required");
        else
            query.append(" and bd.fund.id=").append(Integer.valueOf(queryParamMap.get("fundId").toString()));
    if (!isNull(grpByVls.get("department")))
        if (isNull(queryParamMap.get("ExecutionDepartmentId")))
            throw new ValidationException(EMPTY_STRING, "Department is required");
        else
            query.append(" and bd.executingDepartment.id=")
                    .append(Integer.valueOf(queryParamMap.get("ExecutionDepartmentId").toString()));
    if (!isNull(grpByVls.get("function")))
        if (isNull(queryParamMap.get("functionId")))
            throw new ValidationException(EMPTY_STRING, "Function is required");
        else
            query.append(" and bd.function.id=")
                    .append(Long.valueOf(queryParamMap.get("functionId").toString()));
    if (!isNull(grpByVls.get("scheme")))
        if (isNull(queryParamMap.get("schemeId")))
            throw new ValidationException(EMPTY_STRING, "Scheme is required");
        else
            query.append(" and bd.scheme.id=")
                    .append(Integer.valueOf(queryParamMap.get("schemeId").toString()));
    if (!isNull(grpByVls.get("subscheme")))
        if (isNull(queryParamMap.get("subschemeId")))
            throw new ValidationException(EMPTY_STRING, "SubScheme is required");
        else
            query.append(" and bd.subScheme.id=")
                    .append(Integer.valueOf(queryParamMap.get("subschemeId").toString()));
    if (!isNull(grpByVls.get(Constants.FUNCTIONARY)))
        if (isNull(queryParamMap.get("functionaryId")))
            throw new ValidationException(EMPTY_STRING, "Functionary is required");
        else
            query.append(" and bd.functionary.id=")
                    .append(Integer.valueOf(queryParamMap.get("functionaryId").toString()));
    if (!isNull(grpByVls.get("boundary")))
        if (isNull(queryParamMap.get("boundaryId")))
            throw new ValidationException(EMPTY_STRING, "Boundary is required");
        else
            query.append(" and bd.boundary.id=")
                    .append(Integer.valueOf(queryParamMap.get("boundaryId").toString()));
    if (!isNull(queryParamMap.get("moduleId")))
        query.append(" and bu.moduleId=").append(Integer.valueOf(queryParamMap.get("moduleId").toString()));
    if (!isNull(queryParamMap.get("financialYearId")))
        query.append(" and bu.financialYearId=")
                .append(Integer.valueOf(queryParamMap.get("financialYearId").toString()));
    if (!isNull(queryParamMap.get("budgetgroupId")))
        query.append(" and bd.budgetGroup.id=")
                .append(Long.valueOf(queryParamMap.get("budgetgroupId").toString()));
    if (!isNull(queryParamMap.get("fromDate")))
        query.append(" and bu.updatedTime >=:from");
    if (!isNull(queryParamMap.get("toDate")))
        query.append(" and bu.updatedTime <=:to");
    if (!isNull(queryParamMap.get("Order By"))) {
        if (queryParamMap.get("Order By").toString().indexOf("appropriationnumber") == -1
                && queryParamMap.get("Order By").toString().indexOf("referenceNumber") == -1)
            throw new ValidationException(EMPTY_STRING,
                    "order by value can be only Budgetary appropriation number or Reference number or both");
        else
            query.append(" Order By ").append(queryParamMap.get("Order By"));
    } else
        query.append(" Order By bu.updatedTime");

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Budget Usage Query >>>>>>>> " + query.toString());
    final Query query1 = getCurrentSession().createQuery(query.toString());
    if (!isNull(queryParamMap.get("fromDate")))
        query1.setTimestamp("from", (Date) queryParamMap.get("fromDate"));
    if (!isNull(queryParamMap.get("toDate"))) {
        final Date date = (Date) queryParamMap.get("toDate");
        date.setMinutes(59);
        date.setHours(23);
        date.setSeconds(59);
        query1.setTimestamp("to", date);
    }

    listBudgetUsage = query1.list();
    return listBudgetUsage;

}

From source file:org.egov.egf.commons.EgovCommon.java

License:Open Source License

/**
 * @description - get the list of BudgetUsage based on various parameters
 * @param queryParamMap - HashMap<String, Object> queryParamMap will have data required for the query Query Parameter Map keys
 * are - fundId,ExecutionDepartmentId ,functionId,moduleId,financialYearId ,budgetgroupId,fromDate,toDate and Order By
 * @return//ww  w.j a  v  a  2s.  c om
 */

@SuppressWarnings("unchecked")
public List<BudgetUsage> getListBudgetUsage(final Map<String, Object> queryParamMap) {

    final StringBuffer query = new StringBuffer();
    List<BudgetUsage> listBudgetUsage = null;
    query.append("select bu from BudgetUsage bu,BudgetDetail bd where  bu.budgetDetail.id=bd.id");
    final Map<String, String> mandatoryFields = new HashMap<String, String>();
    final List<AppConfigValues> appConfigList = appConfigValuesService.getConfigValuesByModuleAndKey(
            FinancialConstants.MODULE_NAME_APPCONFIG, "DEFAULTTXNMISATTRRIBUTES");
    for (final AppConfigValues appConfigVal : appConfigList) {
        final String value = appConfigVal.getValue();
        final String header = value.substring(0, value.indexOf("|"));
        final String mandate = value.substring(value.indexOf("|") + 1);
        if (mandate.equalsIgnoreCase("M"))
            mandatoryFields.put(header, "M");
    }
    if (isNotNull(mandatoryFields.get("fund")) && !isNotNull(queryParamMap.get("fundId")))
        throw new ValidationException(Arrays.asList(new ValidationError("fund", "fund cannot be null")));
    else if (isNotNull(queryParamMap.get("fundId")))
        query.append(" and bd.fund.id=").append(Integer.valueOf(queryParamMap.get("fundId").toString()));
    if (isNotNull(mandatoryFields.get("department")) && !isNotNull(queryParamMap.get("ExecutionDepartmentId")))
        throw new ValidationException(
                Arrays.asList(new ValidationError("department", "department cannot be null")));
    else if (isNotNull(queryParamMap.get("ExecutionDepartmentId")))
        query.append(" and bd.executingDepartment.id=")
                .append(Integer.valueOf(queryParamMap.get("ExecutionDepartmentId").toString()));
    if (isNotNull(mandatoryFields.get("function")) && !isNotNull(queryParamMap.get("functionId")))
        throw new ValidationException(
                Arrays.asList(new ValidationError("function", "function cannot be null")));
    else if (isNotNull(queryParamMap.get("functionId")))
        query.append(" and bd.function.id=").append(Long.valueOf(queryParamMap.get("functionId").toString()));

    if (isNotNull(queryParamMap.get("moduleId")))
        query.append(" and bu.moduleId=").append(Integer.valueOf(queryParamMap.get("moduleId").toString()));
    if (isNotNull(queryParamMap.get("financialYearId")))
        query.append(" and bu.financialYearId=")
                .append(Integer.valueOf(queryParamMap.get("financialYearId").toString()));
    if (isNotNull(queryParamMap.get("budgetgroupId")))
        query.append(" and bd.budgetGroup.id=")
                .append(Long.valueOf(queryParamMap.get("budgetgroupId").toString()));
    if (isNotNull(queryParamMap.get("fromDate")))
        query.append(" and bu.updatedTime >=:from");
    if (isNotNull(queryParamMap.get("toDate")))
        query.append(" and bu.updatedTime <=:to");
    if (isNotNull(queryParamMap.get("Order By")))
        query.append(" Order By ").append(queryParamMap.get("Order By"));
    else
        query.append(" Order By bu.updatedTime");

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Budget Usage Query >>>>>>>> " + query.toString());
    final Query query1 = persistenceService.getSession().createQuery(query.toString());
    if (isNotNull(queryParamMap.get("fromDate")))
        query1.setTimestamp("from", (Date) queryParamMap.get("fromDate"));
    if (isNotNull(queryParamMap.get("toDate"))) {
        final Date date = (Date) queryParamMap.get("toDate");
        date.setMinutes(59);
        date.setHours(23);
        date.setSeconds(59);
        query1.setTimestamp("to", date);
    }

    listBudgetUsage = query1.list();
    return listBudgetUsage;

}

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

License:Open Source License

@ValidationErrorPage(value = SEARCH)
@SkipValidation//ww  w . j  a v  a 2  s .  com
@Action(value = "/voucher/cancelVoucher-update")
public String update() {
    CVoucherHeader voucherObj;

    final Date modifiedDate = new Date();
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Inside CancelVoucher| cancelVoucherSubmit | Selected No of Vouchers for cancellation  ="
                + selectedVhs.length);
    final String cancelVhQuery = "Update CVoucherHeader vh set vh.status="
            + FinancialConstants.CANCELLEDVOUCHERSTATUS
            + ",vh.lastModifiedBy.id=:modifiedby, vh.lastModifiedDate=:modifiedDate   where vh.id=:vhId";
    final String cancelVhByCGNQuery = "Update CVoucherHeader vh set vh.status="
            + FinancialConstants.CANCELLEDVOUCHERSTATUS
            + ",vh.lastModifiedBy.id=:modifiedby , vh.lastModifiedDate=:modifiedDate where vh.refvhId=:vhId";
    final String cancelVhByRefCGNQuery = "Update CVoucherHeader vh set vh.status="
            + FinancialConstants.CANCELLEDVOUCHERSTATUS
            + ",vh.lastModifiedBy.id=:modifiedby , vh.lastModifiedDate=:modifiedDate where vh.voucherNumber=:vhNum";
    String voucherId = "";
    final Session session = persistenceService.getSession();
    for (int i = 0; i < selectedVhs.length; i++) {
        voucherObj = (CVoucherHeader) persistenceService.find("from CVoucherHeader vh where vh.id=?",
                selectedVhs[i]);
        final boolean value = cancelBillAndVoucher.canCancelVoucher(voucherObj);

        if (!value) {
            addActionMessage(getText("cancel.voucher.failure", new String[] { voucherObj.getVoucherNumber() }));
            continue;
        }
        voucherId = voucherObj.getId().toString();
        switch (voucherObj.getType()) {

        case FinancialConstants.STANDARD_VOUCHER_TYPE_JOURNAL: {

            final Query query = session.createQuery(cancelVhQuery);
            query.setLong("modifiedby", loggedInUser);
            query.setTimestamp("modifiedDate", modifiedDate);
            query.setLong("vhId", selectedVhs[i]);
            query.executeUpdate();
            // for old vouchers when workflow was not implemented
            if (voucherObj.getState() == null
                    && !voucherObj.getName().equals(FinancialConstants.JOURNALVOUCHER_NAME_GENERAL))
                cancelBill(selectedVhs[i]);
            else if (voucherObj.getState() != null
                    && !voucherObj.getName().equals(FinancialConstants.JOURNALVOUCHER_NAME_GENERAL))
                cancelBill(selectedVhs[i]);
            break;
        }
        case FinancialConstants.STANDARD_VOUCHER_TYPE_PAYMENT: {
            final Query query = session.createQuery(cancelVhQuery);
            query.setLong("vhId", selectedVhs[i]);
            query.setLong("modifiedby", loggedInUser);
            query.setTimestamp("modifiedDate", modifiedDate);
            query.executeUpdate();
            if (FinancialConstants.PAYMENTVOUCHER_NAME_REMITTANCE.equalsIgnoreCase(voucherObj.getName())) {
                int count = paymentService.backUpdateRemittanceDateInGL(voucherHeader.getId());
            }
            break;
        }
        case FinancialConstants.STANDARD_VOUCHER_TYPE_CONTRA: {
            final Query query = session.createQuery(cancelVhQuery);
            query.setLong("vhId", selectedVhs[i]);
            query.setLong("modifiedby", loggedInUser);
            query.setTimestamp("modifiedDate", modifiedDate);
            query.executeUpdate();
            if (FinancialConstants.CONTRAVOUCHER_NAME_INTERFUND.equalsIgnoreCase(voucherObj.getName())) {
                Long vhId;
                vhId = voucherObj.getId();
                final Query queryFnd = session.createQuery(cancelVhByCGNQuery);
                queryFnd.setLong("vhId", vhId);
                queryFnd.setLong("modifiedby", loggedInUser);
                queryFnd.setDate("modifiedDate", modifiedDate);
                queryFnd.executeUpdate();
            }
            break;
        }
        case FinancialConstants.STANDARD_VOUCHER_TYPE_RECEIPT: {
            final Query query = session.createQuery(cancelVhQuery);
            query.setLong("vhId", selectedVhs[i]);
            query.setLong("modifiedby", loggedInUser);
            query.setTimestamp("modifiedDate", modifiedDate);
            query.executeUpdate();
            break;
        }
        }
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug(" Cancel Voucher | CancelVoucher | Vouchers Cancelled ");
    if (voucherId != "")
        addActionMessage(getText("Vouchers Cancelled Succesfully"));
    return SEARCH;
}

From source file:org.gbif.portal.dao.impl.hibernate.SimpleQueryDAOImpl.java

License:Open Source License

/**
 * Create the query setting the positional parameters and limits.
 * /*from   w w  w .j ava2s . c  om*/
 * @param queryString
 * @param parameters
 * @param startIndex
 * @param maxResults
 * @param session
 * @return query ready for execution
 */
private Query createQuery(final String queryString, final List<Object> parameters, final Integer startIndex,
        final Integer maxResults, Session session) {
    Query query = session.createQuery(queryString);
    if (parameters != null) {
        int positionalParamIdx = 0;
        for (int i = 0; i < parameters.size(); i++) {
            // note that the parameter type is inferred here...
            if (logger.isDebugEnabled())
                logger.debug("getByQuery setting parameter " + i + " : " + parameters.get(i));
            if (parameters.get(i) == null) {
                //nulls are handled by not adding
                //any position parameters - setting a position parameter
                //to null or 'null' results in hibernate compiling it down to
                //latitude !=null which behaves differently to is not null
            } else if (parameters.get(i) instanceof Collection) {
                Collection collection = (Collection) parameters.get(i);
                for (Iterator iter = collection.iterator(); iter.hasNext();) {
                    Object parameter = (Object) iter.next();
                    query.setParameter(positionalParamIdx, parameter);
                    positionalParamIdx++;
                }
            } else if (parameters.get(i) instanceof Date) {
                query.setTimestamp(positionalParamIdx, (Date) parameters.get(i));
                positionalParamIdx++;
            } else {
                query.setParameter(positionalParamIdx, parameters.get(i));
                positionalParamIdx++;
            }
        }
    }
    if (startIndex != null)
        query.setFirstResult(startIndex);
    if (maxResults != null)
        query.setMaxResults(maxResults);
    return query;
}

From source file:org.glite.security.voms.admin.persistence.dao.VOMSUserDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<VOMSUser> findAUPFailingUsers(AUP aup) {

    List<VOMSUser> result = new ArrayList<VOMSUser>();

    AUPVersion activeVersion = aup.getActiveVersion();

    // Get users First that do not have any acceptance records for the
    // active aupVersion
    String noAcceptanceRecordForActiveAUPVersionQuery = "select u from VOMSUser u where u not in (select u from VOMSUser u join u.aupAcceptanceRecords r where r.aupVersion.active = true)";

    Query q = HibernateFactory.getSession().createQuery(noAcceptanceRecordForActiveAUPVersionQuery);

    List<VOMSUser> noRecordUsers = q.list();

    result.addAll(noRecordUsers);/*ww w.  j  a  v a2 s .c o  m*/

    log.debug("Users without acceptance records for currently active aup: {}", result);

    // Add users that have an expired aup acceptance record due to aup
    // update or acceptance retriggering.
    String qString = "select u from VOMSUser u join u.aupAcceptanceRecords r where r.aupVersion.active = true and r.lastAcceptanceDate < :lastUpdateTime";

    Query q2 = HibernateFactory.getSession().createQuery(qString);

    Date aupLastUpdateTime = activeVersion.getLastUpdateTime();

    log.debug("AUP version lastUpdateTime: {}", aupLastUpdateTime);
    q2.setTimestamp("lastUpdateTime", aupLastUpdateTime);

    List<VOMSUser> expiredDueToAUPUpdateUsers = q2.list();
    result.addAll(expiredDueToAUPUpdateUsers);

    log.debug("Users that signed the AUP before it was last updated:" + expiredDueToAUPUpdateUsers);

    // Add users that have a valid aup acceptance record that needs to be
    // checked against
    // the reacceptance period
    Query q3 = HibernateFactory.getSession().createQuery(
            "select u from VOMSUser u join u.aupAcceptanceRecords r where r.aupVersion.active = true"
                    + " and r.lastAcceptanceDate > :lastUpdateTime ");

    q3.setTimestamp("lastUpdateTime", aupLastUpdateTime);

    List<VOMSUser> potentiallyExpiredUsers = q3.list();
    HibernateFactory.getSession().flush();

    log.debug("Users that needs checking since their aup acceptance record could be expired:"
            + potentiallyExpiredUsers);

    for (VOMSUser u : potentiallyExpiredUsers) {

        AUPAcceptanceRecord r = u.getAUPAccceptanceRecord(aup.getActiveVersion());

        if (r.hasExpired()) {
            log.debug("Adding user{} to results due to expired aup acceptance report (aup validity expiration)",
                    u);
            result.add(u);

        }

    }

    // Filter out expired users
    ListIterator<VOMSUser> iter = result.listIterator();
    while (iter.hasNext()) {
        VOMSUser u = iter.next();
        if (u.hasExpired() && u.isSuspended()) {
            log.debug("Removing supended user {} from results since " + "membership expired", u);
            iter.remove();
        }
    }

    return result;

}

From source file:org.headsupdev.agile.app.ci.CIApplication.java

License:Open Source License

public static Build getPreviousChangePassed(Build current, Project project) {
    Build build = null;//from w w  w.java  2 s  .  c  o m
    Session session = ((HibernateStorage) Manager.getStorageInstance()).getHibernateSession();

    Query q = session.createQuery("from Build b where id.project.id = :pid and status = "
            + Build.BUILD_SUCCEEDED + " and startTime < :beforeDate order by endTime desc");
    q.setString("pid", project.getId());
    q.setTimestamp("beforeDate", current.getStartTime());
    q.setMaxResults(1);
    List<Build> builds = q.list();
    if (builds.size() > 0) {
        build = builds.get(0);
    }

    return build;
}