Example usage for org.hibernate Criteria setResultTransformer

List of usage examples for org.hibernate Criteria setResultTransformer

Introduction

In this page you can find the example usage for org.hibernate Criteria setResultTransformer.

Prototype

public Criteria setResultTransformer(ResultTransformer resultTransformer);

Source Link

Document

Set a strategy for handling the query results.

Usage

From source file:com.hypersocket.session.SessionRepositoryImpl.java

License:Open Source License

@Override
public Long getSessionCount(final Date startDate, final Date endDate, final boolean distinctUsers) {

    Criteria criteria = createCriteria(Session.class);

    criteria.add(Restrictions.or(/*from  w ww  .  j  a v  a2s. co m*/
            Restrictions.and(Restrictions.ge("created", startDate), Restrictions.lt("created", endDate)),
            Restrictions.and(Restrictions.lt("created", startDate), Restrictions
                    .or(Restrictions.ge("signedOut", startDate), Restrictions.isNull("signedOut")))));

    criteria.add(Restrictions.eq("system", false));

    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    if (distinctUsers) {
        criteria.setProjection(Projections.countDistinct("principal"));
    } else {
        criteria.setProjection(Projections.rowCount());
    }
    return (long) criteria.uniqueResult();
}

From source file:com.hyzy.core.orm.hibernate.HibernateDao.java

License:Apache License

/**
 * countCriteria.//from  w ww .j  av a 2s  . com
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected long countCriteriaResult(final Criteria c) {
    CriteriaImpl impl = (CriteriaImpl) c;

    // Projection?ResultTransformer?OrderBy??,??Count?
    Projection projection = impl.getProjection();
    ResultTransformer transformer = impl.getResultTransformer();

    List<CriteriaImpl.OrderEntry> orderEntries = null;
    try {
        orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");
        ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
    } catch (Exception e) {
        logger.error("??:{}", e.getMessage());
    }

    // Count
    Long totalCountObject = 0l;
    try {
        totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
    } catch (Exception e) {
        e.printStackTrace();
    }
    long totalCount = (totalCountObject != null) ? totalCountObject : 0;

    // ?Projection,ResultTransformerOrderBy??
    c.setProjection(projection);

    if (projection == null) {
        c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
    }
    if (transformer != null) {
        c.setResultTransformer(transformer);
    }
    try {
        ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
    } catch (Exception e) {
        logger.error("??:{}", e.getMessage());
    }

    return totalCount;
}

From source file:com.ibm.asset.trails.dao.jpa.VSoftwareLparDAOJpa.java

public void paginatedList(DisplayTagList data, Account account, ReconSetting reconSetting, int startIndex,
        int objectsPerPage, String sort, String dir) {
    Criteria criteria = getHibernateSessionCriteria();

    criteria.createAlias("hardwareLpar", "hl")
            .createAlias("hl.hardwareLparEff", "hle", CriteriaSpecification.LEFT_JOIN)
            .createAlias("hl.hardware", "h").createAlias("h.machineType", "mt")
            .createAlias("installedSoftwares", "is")
            .createAlias("is.scheduleF", "sf", CriteriaSpecification.LEFT_JOIN)
            .createAlias("sf.scope", "scope", CriteriaSpecification.LEFT_JOIN)
            .createAlias("is.softwareLpar", "sl").createAlias("is.alert", "aus")
            .createAlias("aus.reconcile", "r", CriteriaSpecification.LEFT_JOIN)
            .createAlias("r.usedLicenses", "ul", CriteriaSpecification.LEFT_JOIN)
            .createAlias("ul.license", "license", CriteriaSpecification.LEFT_JOIN)
            .createAlias("r.reconcileType", "rt", CriteriaSpecification.LEFT_JOIN)
            .createAlias("is.software", "sw")
            .createAlias("sw.manufacturer", "mf", CriteriaSpecification.LEFT_JOIN)
            .add(Restrictions.eq("account", account));

    if (reconSetting.getReconcileType() != null) {
        criteria.add(Restrictions.eq("rt.id", reconSetting.getReconcileType()));
    }//  w w  w.  j  a  v a  2  s  . c  o  m

    if (StringUtils.isNotBlank(reconSetting.getAlertStatus())) {
        boolean open = false;
        if (reconSetting.getAlertStatus().equals("OPEN")) {
            open = true;
            criteria.add(Restrictions.eq("aus.open", open));
        } else {
            criteria.add(Restrictions.and(Restrictions.eq("aus.open", false),
                    Restrictions.eqProperty("is.id", "r.installedSoftware.id")));
        }

    } else {
        criteria.add(Restrictions.or(Restrictions.eq("aus.open", true),
                Restrictions.and(Restrictions.eq("aus.open", false),
                        Restrictions.eqProperty("is.id", "r.installedSoftware.id"))));
    }

    if (null != reconSetting.getAlertFrom() && reconSetting.getAlertFrom().intValue() >= 0) {
        criteria.add(Restrictions.ge("aus.alertAge", reconSetting.getAlertFrom()));
    }
    if (null != reconSetting.getAlertTo() && reconSetting.getAlertTo().intValue() >= 0) {
        criteria.add(Restrictions.le("aus.alertAge", reconSetting.getAlertTo()));
    }

    if (StringUtils.isNotBlank(reconSetting.getAssigned())) {
        if (reconSetting.getAssigned().equals("Assigned")) {
            criteria.add(Restrictions.ne("aus.remoteUser", "STAGING"));
        }
        if (reconSetting.getAssigned().equals("Unassigned")) {
            criteria.add(Restrictions.eq("aus.remoteUser", "STAGING"));
        }
    }

    if (StringUtils.isNotBlank(reconSetting.getAssignee())) {
        criteria.add(Restrictions.eq("aus.remoteUser", reconSetting.getAssignee()).ignoreCase());
    }

    if (StringUtils.isNotBlank(reconSetting.getOwner())) {
        if (reconSetting.getOwner().equalsIgnoreCase("IBM")) {
            criteria.add(Restrictions.eq("h.owner", reconSetting.getOwner()).ignoreCase());
        } else if (reconSetting.getOwner().equalsIgnoreCase("Customer")) {
            ArrayList<String> lalOwner = new ArrayList<String>();

            lalOwner.add("CUST");
            lalOwner.add("CUSTO");
            criteria.add(Restrictions.in("h.owner", lalOwner));
        }
    }

    // I'm not sure why the heck we aren't just getting a list of strings?
    if (reconSetting.getCountries().length > 0) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < reconSetting.getCountries().length; i++) {
            if (StringUtils.isNotBlank(reconSetting.getCountries()[i])) {
                list.add(reconSetting.getCountries()[i].toUpperCase());
            }
        }

        if (list.size() > 0) {
            criteria.add(Restrictions.in("h.country", list));
        }
    }

    if (reconSetting.getNames().length > 0) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < reconSetting.getNames().length; i++) {
            if (StringUtils.isNotBlank(reconSetting.getNames()[i])) {
                list.add(reconSetting.getNames()[i].toUpperCase());
            }
        }

        if (list.size() > 0) {
            criteria.add(Restrictions.in("hl.name", list));
        }
    }

    if (reconSetting.getSwcmIDs().length > 0) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < reconSetting.getSwcmIDs().length; i++) {
            if (StringUtils.isNotBlank(reconSetting.getSwcmIDs()[i])) {
                list.add(reconSetting.getSwcmIDs()[i].toUpperCase());
            }
        }
        if (list.size() > 0) {
            criteria.add(Restrictions.in("license.extSrcId", list));
        }
    }

    if (reconSetting.getSerialNumbers().length > 0) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < reconSetting.getSerialNumbers().length; i++) {
            if (StringUtils.isNotBlank(reconSetting.getSerialNumbers()[i])) {
                list.add(reconSetting.getSerialNumbers()[i].toUpperCase());
            }
        }

        if (list.size() > 0) {
            criteria.add(Restrictions.in("h.serial", list));
        }
    }

    if (reconSetting.getProductInfoNames().length > 0) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < reconSetting.getProductInfoNames().length; i++) {
            if (StringUtils.isNotBlank(reconSetting.getProductInfoNames()[i])) {
                list.add(reconSetting.getProductInfoNames()[i]);
            }
        }

        if (list.size() > 0) {
            criteria.add(Restrictions.in("sw.softwareName", list));
        }
    }

    if (StringUtils.isNotBlank(reconSetting.getScope())) {
        if ("Not specified".equalsIgnoreCase(reconSetting.getScope())) {
            criteria.add(Restrictions.isNull("scope.description"));
        } else {
            criteria.add(Restrictions.eq("scope.description", reconSetting.getScope()));
        }
    }

    if (StringUtils.isNotBlank(reconSetting.getFinanResp())) {
        if ("Not Specified".trim().equalsIgnoreCase(reconSetting.getFinanResp())) {
            criteria.add(Restrictions.isNull("sf.SWFinanceResp"));
        } else {
            criteria.add(Restrictions.eq("sf.SWFinanceResp", reconSetting.getFinanResp()));
        }
    }

    criteria.setProjection(Projections.projectionList().add(Projections.property("aus.id").as("alertId"))
            .add(Projections.property("r.id").as("reconcileId"))
            .add(Projections.property("aus.alertAge").as("alertAgeI"))
            .add(Projections.property("is.id").as("installedSoftwareId"))
            .add(Projections.property("hl.name").as("hostname"))
            .add(Projections.property("sl.name").as("sl_hostname"))
            .add(Projections.property("hl.spla").as("spla"))
            .add(Projections.property("hl.sysplex").as("sysplex"))
            .add(Projections.property("hl.internetIccFlag").as("internetIccFlag"))
            .add(Projections.property("h.serial").as("serial"))
            .add(Projections.property("h.country").as("country"))
            .add(Projections.property("h.owner").as("owner"))
            .add(Projections.property("h.mastProcessorType").as("mastProcessorType"))
            .add(Projections.property("h.processorManufacturer").as("processorManufacturer"))
            .add(Projections.property("h.mastProcessorModel").as("mastProcessorModel"))
            .add(Projections.property("h.nbrCoresPerChip").as("nbrCoresPerChip"))
            .add(Projections.property("h.nbrOfChipsMax").as("nbrOfChipsMax"))
            .add(Projections.property("h.cpuLsprMips").as("cpuLsprMips"))
            .add(Projections.property("h.cpuIfl").as("cpuIFL"))
            .add(Projections.property("hl.partLsprMips").as("partLsprMips"))
            .add(Projections.property("h.cpuGartnerMips").as("cpuGartnerMips"))
            .add(Projections.property("hl.partGartnerMips").as("partGartnerMips"))
            .add(Projections.property("hl.effectiveThreads").as("effectiveThreads"))
            .add(Projections.property("hl.vcpu").as("vcpu")).add(Projections.property("h.cpuMsu").as("cpuMsu"))
            .add(Projections.property("hl.partMsu").as("partMsu"))
            .add(Projections.property("hl.serverType").as("lparServerType"))
            .add(Projections.property("h.shared").as("shared"))
            .add(Projections.property("h.multi_tenant").as("multi_tenant"))
            .add(Projections.property("mt.type").as("assetType"))
            .add(Projections.property("mt.name").as("assetName"))
            .add(Projections.property("h.hardwareStatus").as("hardwareStatus"))
            .add(Projections.property("hl.lparStatus").as("lparStatus"))
            .add(Projections.property("processorCount").as("processorCount"))
            .add(Projections.property("sw.softwareName").as("productInfoName"))
            .add(Projections.property("sw.softwareId").as("productInfoId"))
            .add(Projections.property("sw.pid").as("pid"))
            .add(Projections.property("mf.manufacturerName").as("manufacturerName"))
            .add(Projections.property("rt.name").as("reconcileTypeName"))
            .add(Projections.property("rt.id").as("reconcileTypeId"))
            .add(Projections.property("aus.remoteUser").as("assignee"))
            .add(Projections.property("h.processorCount").as("hardwareProcessorCount"))
            .add(Projections.property("hle.processorCount").as("hwLparEffProcessorCount"))
            .add(Projections.property("hl.osType").as("osType"))
            .add(Projections.property("hle.status").as("hwLparEffProcessorStatus"))
            .add(Projections.property("h.chips").as("chips")));
    criteria.setResultTransformer(new AliasToBeanResultTransformer(ReconWorkspace.class));

    criteria.addOrder(Order.desc("aus.open"));

    if (dir.equalsIgnoreCase("ASC")) {
        criteria.addOrder(Order.asc(sort));
    } else {
        criteria.addOrder(Order.desc(sort));
    }

    ArrayList<ReconWorkspace> list = new ArrayList<ReconWorkspace>();

    ScrollableResults itemCursor = criteria.scroll();
    itemCursor.beforeFirst();
    if (itemCursor.next()) {
        itemCursor.scroll(startIndex);
        int i = 0;

        while (objectsPerPage > i++) {
            ReconWorkspace rw = (ReconWorkspace) itemCursor.get(0);
            if (null != rw.getHwLparEffProcessorStatus()
                    && rw.getHwLparEffProcessorStatus().equalsIgnoreCase("INACTIVE")) {
                rw.setHwLparEffProcessorCount(0);
            }
            list.add(rw);
            if (!itemCursor.next())
                break;
        }

        data.setList(list);
        itemCursor.last();
        data.setFullListSize(itemCursor.getRowNumber() + 1);
        itemCursor.close();

        addSchedulef2List(account, data.getList());
    } else {
        data.setList(null);
        data.setFullListSize(0);
        itemCursor.close();
    }

}

From source file:com.ignou.aadhar.dao.hibernate.BankDaoHibernate.java

License:Open Source License

/**
 * Gets the records from the Database based on the parameters provided.
 * @param searchField The field name on which the search is to be made.
 * @param searchValue Value which needs to be searched.
 * @param pageNumber Initial offset of the records.
 * @param recordsPerPage Total number of records which are selected for
 * resultset.// w  w w  . j av  a2 s  . c om
 * @param sortField Name of the field on which the data needs to be sorted.
 * @param sortOrder Order in which the sortField is sorted.
 * @return Returns the records as list of map where each map stores the
 * record data as key-value pairs.
 */
@Override
public List<Map<String, Object>> getBanks(String searchField, String searchValue, Integer pageNumber,
        Integer recordsPerPage, String sortField, String sortOrder) {

    List<Bank> banks = null;
    List<Map<String, Object>> returnBanks = new ArrayList<Map<String, Object>>();

    Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Bank.class);

    /* Add the search parameters to the criteria */
    if (searchField != null && !searchField.isEmpty() && searchValue != null && !searchValue.isEmpty()) {

        /* Prefix and suffix the searchValue with % */
        searchValue = "%" + searchValue + "%";

        /* Now there are only two fields which we can search here. */
        if ("name".equals(searchField)) {
            criteria.add(Restrictions.ilike("name", searchValue));
        } else if ("url".equals(searchField)) {
            criteria.add(Restrictions.ilike("url", searchValue));
        }
    }

    /* Let's first get the total number of records that satisfy the provided
     * parameters.
     */
    String totalCount = (String) criteria.setProjection(Projections.rowCount()).uniqueResult().toString();

    /* Reset the Criteria specification to remove the projection details */
    criteria.setProjection(null);
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    /* Set the default sort field if not provided */
    if (sortField != null && !sortField.isEmpty()) {

        /* Check what order was provided for this field */
        if ("asc".equals(sortOrder)) {
            /* Sort in ascending order */
            criteria.addOrder(Order.asc(sortField));

        } else if ("desc".equals(sortOrder)) {
            /* Sort in descending order */
            criteria.addOrder(Order.desc(sortField));

        } else {
            /* Default sort behaviour other wise */
            criteria.addOrder(Order.asc(sortField));
        }
    }

    /* Set the record filtering on pageCount and recordsPerPage if they are
     * available.
     */
    if (pageNumber != null && recordsPerPage != null) {
        banks = criteria.setFirstResult(pageNumber).setMaxResults(recordsPerPage).list();
    } else {
        banks = criteria.list();
    }

    /* Format this data before sending back for any other further usage */
    for (Bank bankRecord : banks) {

        /* Create new map for current bank and add it to master list */
        Map<String, Object> returnMap = new LinkedHashMap<String, Object>();
        returnMap.put("id", bankRecord.getId());
        returnMap.put("name", bankRecord.getName());
        returnMap.put("url", bankRecord.getUrl());
        returnMap.put("totalCount", totalCount);

        returnBanks.add(returnMap);
    }

    return returnBanks;
}

From source file:com.ignou.aadhar.dao.hibernate.CityDaoHibernate.java

License:Open Source License

/**
 * Gets the records from the Database based on the parameters provided.
 * @param searchField The field name on which the search is to be made.
 * @param searchValue Value which needs to be searched.
 * @param pageNumber Initial offset of the records.
 * @param recordsPerPage Total number of records which are selected for
 * resultset.//from  w w  w.j a va 2s .  c om
 * @param sortField Name of the field on which the data needs to be sorted.
 * @param sortOrder Order in which the sortField is sorted.
 * @return Returns the records as list of map where each map stores the
 * record data as key-value pairs.
 */
@Override
public List<Map<String, Object>> getCities(String searchField, String searchValue, Integer pageNumber,
        Integer recordsPerPage, String sortField, String sortOrder) {

    List<City> cities = null;
    List<Map<String, Object>> returnCities = new ArrayList<Map<String, Object>>();

    Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(City.class, "c")
            .createAlias("state", "s");

    /* Add the search parameters to the criteria */
    if (searchField != null && !searchField.isEmpty() && searchValue != null && !searchValue.isEmpty()) {

        /* Prefix and suffix the searchValue with % */
        searchValue = "%" + searchValue + "%";

        /* Now there are only two fields which we can search here. */
        if ("city".equals(searchField)) {
            criteria.add(Restrictions.ilike("c.city", searchValue));
        } else if ("state".equals(searchField)) {
            criteria.add(Restrictions.ilike("s.state", searchValue));
        }
    }

    /* Let's first get the total number of records that satisfy the provided
     * parameters.
     */
    String totalCount = (String) criteria.setProjection(Projections.rowCount()).uniqueResult().toString();

    /* Reset the Criteria specification to remove the projection details */
    criteria.setProjection(null);
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    /* Set the default sort field if not provided */
    if (sortField != null && !sortField.isEmpty()) {

        /* Check what order was provided for this field */
        if ("asc".equals(sortOrder)) {
            /* Sort in ascending order */
            criteria.addOrder(Order.asc(sortField));

        } else if ("desc".equals(sortOrder)) {
            /* Sort in descending order */
            criteria.addOrder(Order.desc(sortField));

        } else {
            /* Default sort behaviour other wise */
            criteria.addOrder(Order.asc(sortField));
        }
    }

    /* We don't want to load the entire objects. Just the names would
     * suffice. Setting projections for the same.
     */
    //criteria.setProjection(Projections.property("id").as("id"));
    //criteria.setProjection(Projections.property("city").as("city"));
    //criteria.setProjection(Projections.property("state").as("state"));

    /* Set the record filtering on pageCount and recordsPerPage if they are
     * available.
     */
    if (pageNumber != null && recordsPerPage != null) {
        cities = criteria.setFirstResult(pageNumber).setMaxResults(recordsPerPage).list();
    } else {
        cities = criteria.list();
    }

    /* Format this data before sending back for any other further usage */
    for (City cityRecord : cities) {

        /* Create a new map for current city and add it to master list */
        Map<String, Object> returnMap = new LinkedHashMap<String, Object>();
        returnMap.put("id", cityRecord.getId());
        returnMap.put("city", cityRecord.getCity());
        returnMap.put("state", cityRecord.getState().getState());
        returnMap.put("totalCount", totalCount);

        returnCities.add(returnMap);
    }

    return returnCities;
}

From source file:com.ignou.aadhar.dao.hibernate.DistrictDaoHibernate.java

License:Open Source License

/**
 * Gets the records from the Database based on the parameters provided.
 * @param searchField The field name on which the search is to be made.
 * @param searchValue Value which needs to be searched.
 * @param pageNumber Initial offset of the records.
 * @param recordsPerPage Total number of records which are selected for
 * resultset.//  w  w w .  j  av  a2s .c om
 * @param sortField Name of the field on which the data needs to be sorted.
 * @param sortOrder Order in which the sortField is sorted.
 * @return Returns the records as list of map where each map stores the
 * record data as key-value pairs.
 */
@Override
public List<Map<String, Object>> getDistricts(String searchField, String searchValue, Integer pageNumber,
        Integer recordsPerPage, String sortField, String sortOrder) {

    List<District> districts = null;
    List<Map<String, Object>> returnDistricts = new ArrayList<Map<String, Object>>();

    Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(District.class, "d")
            .createAlias("state", "s");

    /* Add the search parameters to the criteria */
    if (searchField != null && !searchField.isEmpty() && searchValue != null && !searchValue.isEmpty()) {

        /* Prefix and suffix the searchValue with % */
        searchValue = "%" + searchValue + "%";

        /* Now there are only two fields which we can search here. */
        if ("district".equals(searchField)) {
            criteria.add(Restrictions.ilike("d.district", searchValue));
        } else if ("state".equals(searchField)) {
            criteria.add(Restrictions.ilike("s.state", searchValue));
        }
    }

    /* Let's first get the total number of records that satisfy the provided
     * parameters.
     */
    String totalCount = (String) criteria.setProjection(Projections.rowCount()).uniqueResult().toString();

    /* Reset the Criteria specification to remove the projection details */
    criteria.setProjection(null);
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    /* Set the default sort field if not provided */
    if (sortField != null && !sortField.isEmpty()) {

        /* Check what order was provided for this field */
        if ("asc".equals(sortOrder)) {
            /* Sort in ascending order */
            criteria.addOrder(Order.asc(sortField));

        } else if ("desc".equals(sortOrder)) {
            /* Sort in descending order */
            criteria.addOrder(Order.desc(sortField));

        } else {
            /* Default sort behaviour other wise */
            criteria.addOrder(Order.asc(sortField));
        }
    }

    /* Set the record filtering on pageCount and recordsPerPage if they are
     * available.
     */
    if (pageNumber != null && recordsPerPage != null) {
        districts = criteria.setFirstResult(pageNumber).setMaxResults(recordsPerPage).list();
    } else {
        districts = criteria.list();
    }

    /* Format this data before sending back for any other further usage */
    for (District districtRecord : districts) {

        /* Create new map for current district and add it to master list */
        Map<String, Object> returnMap = new LinkedHashMap<String, Object>();
        returnMap.put("id", districtRecord.getId());
        returnMap.put("district", districtRecord.getDistrict());
        returnMap.put("state", districtRecord.getState().getState());
        returnMap.put("totalCount", totalCount);

        returnDistricts.add(returnMap);
    }

    return returnDistricts;
}

From source file:com.ignou.aadhar.dao.hibernate.ServiceProviderDaoHibernate.java

License:Open Source License

/**
 * Gets the records from the Database based on the parameters provided.
 * @param searchField The field name on which the search is to be made.
 * @param searchValue Value which needs to be searched.
 * @param pageNumber Initial offset of the records.
 * @param recordsPerPage Total number of records which are selected for
 * resultset.//from  www .j  ava2 s  .  c  o m
 * @param sortField Name of the field on which the data needs to be sorted.
 * @param sortOrder Order in which the sortField is sorted.
 * @return Returns the records as list of map where each map stores the
 * record data as key-value pairs.
 */
@Override
public List<Map<String, Object>> getServiceProviders(String searchField, String searchValue, Integer pageNumber,
        Integer recordsPerPage, String sortField, String sortOrder) {

    List<ServiceProvider> records = null;
    List<Map<String, Object>> returnRecords = new ArrayList<Map<String, Object>>();

    Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(ServiceProvider.class);

    /* Add the search parameters to the criteria */
    if (searchField != null && !searchField.isEmpty() && searchValue != null && !searchValue.isEmpty()) {

        /* Prefix and suffix the searchValue with % */
        searchValue = "%" + searchValue + "%";

        /* Set the matching field accordingly */
        if ("name".equals(searchField)) {
            criteria.add(Restrictions.ilike("name", searchValue));

        } else if ("requestUrl".equals(searchField)) {
            criteria.add(Restrictions.ilike("requestUrl", searchValue));

        } else if ("responseUrl".equals(searchField)) {
            criteria.add(Restrictions.ilike("responseUrl", searchValue));

        } else if ("accountNumber".equals(searchField)) {
            criteria.add(Restrictions.ilike("accountNumber", searchValue));

        } else if ("bankIFSCode".equals(searchField)) {
            criteria.add(Restrictions.ilike("bankIFSCode", searchValue));

        }
    }

    /* Let's first get the total number of records that satisfy the provided
     * parameters.
     */
    String totalCount = (String) criteria.setProjection(Projections.rowCount()).uniqueResult().toString();

    /* Reset the Criteria specification to remove the projection details */
    criteria.setProjection(null);
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    /* Set the default sort field if not provided */
    if (sortField != null && !sortField.isEmpty()) {

        /* Check what order was provided for this field */
        if ("asc".equals(sortOrder)) {
            /* Sort in ascending order */
            criteria.addOrder(Order.asc(sortField));

        } else if ("desc".equals(sortOrder)) {
            /* Sort in descending order */
            criteria.addOrder(Order.desc(sortField));

        } else {
            /* Default sort behaviour other wise */
            criteria.addOrder(Order.asc(sortField));
        }
    }

    /* Set the record filtering on pageCount and recordsPerPage if they are
     * available.
     */
    if (pageNumber != null && recordsPerPage != null) {
        records = criteria.setFirstResult(pageNumber).setMaxResults(recordsPerPage).list();
    } else {
        records = criteria.list();
    }

    /* Format this data before sending back for any other further usage */
    for (ServiceProvider serviceProvider : records) {

        /* Create new map for current service provider and add it to
         * master list
         */
        Map<String, Object> returnMap = new LinkedHashMap<String, Object>();
        returnMap.put("id", serviceProvider.getId());
        returnMap.put("name", serviceProvider.getName());
        returnMap.put("requestUrl", serviceProvider.getRequestUrl());
        returnMap.put("responseUrl", serviceProvider.getResponseUrl());
        returnMap.put("accountNumber", serviceProvider.getAccountNumber());
        returnMap.put("bankIFSCCode", serviceProvider.getBankIFSCCode());
        returnMap.put("totalCount", totalCount);

        returnRecords.add(returnMap);
    }

    return returnRecords;
}

From source file:com.ignou.aadhar.dao.hibernate.StateDaoHibernate.java

License:Open Source License

/**
 * Gets the records from the Database based on the parameters provided.
 * @param searchField The field name on which the search is to be made.
 * @param searchValue Value which needs to be searched.
 * @param pageNumber Initial offset of the records.
 * @param recordsPerPage Total number of records which are selected for
 * resultset.//from   w  w  w .j  a v a 2  s . c o  m
 * @param sortField Name of the field on which the data needs to be sorted.
 * @param sortOrder Order in which the sortField is sorted.
 * @return Returns the records as list of map where each map stores the
 * record data as key-value pairs.
 */
@Override
public List<Map<String, Object>> getStates(String searchField, String searchValue, Integer pageNumber,
        Integer recordsPerPage, String sortField, String sortOrder) {

    List<State> states = null;
    List<Map<String, Object>> returnStates = new ArrayList<Map<String, Object>>();

    Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(State.class, "s");

    /* Add the search parameters to the criteria */
    if (searchField != null && !searchField.isEmpty() && searchValue != null && !searchValue.isEmpty()) {

        /* Prefix and suffix the searchValue with % */
        searchValue = "%" + searchValue + "%";
        criteria.add(Restrictions.ilike("s.state", searchValue));
    }

    /* Let's first get the total number of records that satisfy the provided
     * parameters.
     */
    String totalCount = (String) criteria.setProjection(Projections.rowCount()).uniqueResult().toString();

    /* Reset the Criteria specification to remove the projection details */
    criteria.setProjection(null);
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    /* Set the default sort field if not provided */
    if (sortField != null && !sortField.isEmpty()) {

        /* Check what order was provided for this field */
        if ("asc".equals(sortOrder)) {
            /* Sort in ascending order */
            criteria.addOrder(Order.asc(sortField));

        } else if ("desc".equals(sortOrder)) {
            /* Sort in descending order */
            criteria.addOrder(Order.desc(sortField));

        } else {
            /* Default sort behaviour other wise */
            criteria.addOrder(Order.asc(sortField));
        }
    }

    /* Set the record filtering on pageCount and recordsPerPage if they are
     * available.
     */
    if (pageNumber != null && recordsPerPage != null) {
        states = criteria.setFirstResult(pageNumber).setMaxResults(recordsPerPage).list();
    } else {
        states = criteria.list();
    }

    /* Format this data before sending back for any other further usage */
    for (State stateRecord : states) {

        /* Create new map for current state and add it to master list */
        Map<String, Object> returnMap = new LinkedHashMap<String, Object>();
        returnMap.put("id", stateRecord.getId());
        returnMap.put("state", stateRecord.getState());
        returnMap.put("totalCount", totalCount);

        returnStates.add(returnMap);
    }

    return returnStates;
}

From source file:com.ignou.aadhar.dao.hibernate.TransactionDaoHibernate.java

License:Open Source License

/**
 * Gets the records from the Database based on the parameters provided.
 * @param searchField The field name on which the search is to be made.
 * @param searchValue Value which needs to be searched.
 * @param pageNumber Initial offset of the records.
 * @param recordsPerPage Total number of records which are selected for
 * resultset./* w w w  .  j a  v  a  2s.  c om*/
 * @param sortField Name of the field on which the data needs to be sorted.
 * @param sortOrder Order in which the sortField is sorted.
 * @return Returns the records as list of map where each map stores the
 * record data as key-value pairs.
 */
@Override
@Transactional
public List<Map<String, Object>> getTransactions(String searchField, String searchValue, Integer pageNumber,
        Integer recordsPerPage, String sortField, String sortOrder) {

    List<Transaction> records = null;
    List<Map<String, Object>> returnRecords = new ArrayList<Map<String, Object>>();

    Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Transaction.class);

    /* Add the search parameters to the criteria */
    if (searchField != null && !searchField.isEmpty() && searchValue != null && !searchValue.isEmpty()) {

        /* Prefix and suffix the searchValue with % */
        searchValue = "%" + searchValue + "%";

        /* Set the matching field accordingly */
        if ("uid".equals(searchField)) {
            criteria.add(Restrictions.ilike("citizen.uid", searchValue));

        } else if ("serviceprovider".equals(searchField)) {
            criteria.add(Restrictions.ilike("serviceProvider.name", searchValue));

        } else if ("clientTxnId".equals(searchField)) {
            criteria.add(Restrictions.ilike("spTransactionId", searchValue));

        } else if ("bankTxnId".equals(searchField)) {
            criteria.add(Restrictions.ilike("bankTransactionId", searchValue));

        } else if ("status".equals(searchField)) {
            criteria.add(Restrictions.ilike("status", searchValue));

        }
    }

    /* Let's first get the total number of records that satisfy the provided
     * parameters.
     */
    String totalCount = (String) criteria.setProjection(Projections.rowCount()).uniqueResult().toString();

    /* Reset the Criteria specification to remove the projection details */
    criteria.setProjection(null);
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    /* Set the default sort field if not provided */
    if (sortField != null && !sortField.isEmpty()) {

        /* Check what order was provided for this field */
        if ("asc".equals(sortOrder)) {
            /* Sort in ascending order */
            criteria.addOrder(Order.asc(sortField));

        } else if ("desc".equals(sortOrder)) {
            /* Sort in descending order */
            criteria.addOrder(Order.desc(sortField));

        } else {
            /* Default sort behaviour other wise */
            criteria.addOrder(Order.asc(sortField));
        }
    }

    /* Set the record filtering on pageCount and recordsPerPage if they are
     * available.
     */
    if (pageNumber != null && recordsPerPage != null) {
        records = criteria.setFirstResult(pageNumber).setMaxResults(recordsPerPage).list();
    } else {
        records = criteria.list();
    }

    /* Format the Date */
    SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy h:m:s a");

    /* Format this data before sending back for any other further usage */
    for (Transaction transaction : records) {

        /* Create new map for current transaction and add it to
         * master list
         */
        Map<String, Object> returnMap = new LinkedHashMap<String, Object>();
        returnMap.put("id", transaction.getId());
        returnMap.put("uid", transaction.getCitizen().getUid());
        returnMap.put("name", transaction.getCitizen().getName());
        returnMap.put("serviceprovider", transaction.getServiceProvider().getName());
        returnMap.put("clientTxnId", transaction.getSpTransactionId());
        returnMap.put("bankTxnId", transaction.getBankTransactionId());
        returnMap.put("status", transaction.getStatus());
        returnMap.put("created", format.format(transaction.getCreated()));
        returnMap.put("amount", transaction.getAmount());
        returnMap.put("totalCount", totalCount);

        returnRecords.add(returnMap);
    }

    return returnRecords;
}

From source file:com.indicator_engine.dao.GLACategoryDaoImpl.java

License:Open Source License

/**
 * Loads all the Category Items from Database..
 * @param colName Column Name to be used for sorting the results before it returns.
 * @param sortDirection Specifies the Sort Direction : asc or desc
 * @param sort Turn Sorting On or Off.//  www.j a va 2 s  . c o  m
 * @return Returns all the Category Items present in DB.
 */
@Override
@Transactional(readOnly = true)
public List<GLACategory> loadAll(String colName, String sortDirection, boolean sort) {
    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(GLACategory.class);
    criteria.setFetchMode("events", FetchMode.JOIN);
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    if (sort) {
        if (sortDirection.equals("asc"))
            criteria.addOrder(Order.asc(colName));
        else
            criteria.addOrder(Order.desc(colName));
    }
    return criteria.list();
}