Example usage for javax.persistence TypedQuery setFirstResult

List of usage examples for javax.persistence TypedQuery setFirstResult

Introduction

In this page you can find the example usage for javax.persistence TypedQuery setFirstResult.

Prototype

TypedQuery<X> setFirstResult(int startPosition);

Source Link

Document

Set the position of the first result to retrieve.

Usage

From source file:org.openmeetings.app.data.conference.Roommanagement.java

/**
 * gets a list of all availible rooms/*ww  w  .java  2s.  c  om*/
 * 
 * @param user_level
 * @param start
 * @param max
 * @param orderby
 * @param asc
 * @return
 */
public List<Rooms> getRoomsInternatlByHQL(int start, int max, String orderby, boolean asc, String search) {
    try {

        String hql = "select c from Rooms c " + "where c.deleted <> 'true' " + "AND c.name LIKE :search ";

        if (search.length() == 0) {
            search = "%";
        } else {
            search = "%" + search + "%";
        }
        if (orderby != null) {
            hql += " ORDER BY " + (orderby.startsWith("c.") ? "" : "c.") + orderby;

            if (asc) {
                hql += " ASC";
            } else {
                hql += " DESC";
            }
        }
        TypedQuery<Rooms> query = em.createQuery(hql, Rooms.class);
        query.setParameter("search", search);
        query.setFirstResult(start);
        query.setMaxResults(max);

        return query.getResultList();

    } catch (Exception ex2) {
        log.error("[getRooms ] ", ex2);
    }
    return null;
}

From source file:org.openmeetings.app.data.conference.Roommanagement.java

/**
 * /*from  w w  w.  jav a 2  s .  c om*/
 * @param organisation_id
 * @param start
 * @param max
 * @param orderby
 * @param asc
 * @return
 */
private List<Rooms_Organisation> getRoomsOrganisationByOrganisationId(long organisation_id, int start, int max,
        String orderby, boolean asc) {
    try {
        String hql = "select c from Rooms_Organisation as c "
                + "where c.organisation.organisation_id = :organisation_id " + "AND c.deleted <> :deleted";
        if (orderby.startsWith("c.")) {
            hql += "ORDER BY " + orderby;
        } else {
            hql += "ORDER BY " + "c." + orderby;
        }
        if (asc) {
            hql += " ASC";
        } else {
            hql += " DESC";
        }

        TypedQuery<Rooms_Organisation> q = em.createQuery(hql, Rooms_Organisation.class);

        q.setParameter("organisation_id", organisation_id);
        q.setParameter("deleted", "true");
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Rooms_Organisation> ll = q.getResultList();

        return ll;
    } catch (Exception ex2) {
        log.error("[getRoomsByOrganisation] ", ex2);
    }
    return null;
}

From source file:com.hp.triclops.repository.VehicleRepositoryDAO.java

/**
 * /*from  w  w w  .j a va2 s.c o  m*/
 * @param id ?null""??
 * @param vin ?null""??
 * @param vendor ?null""??
 * @param model ?null""??
 * @param t_flag 0 ? 1  ??
 * @param displacement ?null""??
 * @param license_plate ?null""??
 * @param start_date ?null??
 * @param end_date ??null??
 * @param orderByProperty ?? Vehicle?,vin
 * @param ascOrDesc ??? "ASC""DESC"  ???,ASC
 * @param pageSize ??? 0
 * @param currentPage ??? 0
 * @param oid id
 * @return  ????Page
 */
public Page findVehiclesByKeys(Integer id, String vin, String vendor, String model, Integer t_flag,
        String displacement, String license_plate, Date start_date, Date end_date, String orderByProperty,
        String ascOrDesc, Integer pageSize, Integer currentPage, Integer oid) {
    String jpql = "select v FROM Vehicle v";
    String jpql_count = "";
    id = (id == null) ? -1 : id;
    vin = (vin == null) ? "" : EscapeStringUtil.toEscape(vin);
    vendor = (vendor == null) ? "" : vendor;
    model = (model == null) ? "" : model;
    displacement = (displacement == null) ? "" : displacement;
    license_plate = (license_plate == null) ? "" : EscapeStringUtil.toEscape(license_plate);
    orderByProperty = (orderByProperty == null) ? "vin" : orderByProperty;
    ascOrDesc = (ascOrDesc == null) ? "ASC" : ascOrDesc;
    t_flag = (t_flag == null) ? -1 : t_flag;
    pageSize = (pageSize == null) ? 10 : pageSize;
    pageSize = (pageSize <= 0) ? 10 : pageSize;
    currentPage = (currentPage == null) ? 1 : currentPage;
    currentPage = (currentPage <= 0) ? 1 : currentPage;
    if (oid != null && oid >= 0) {
        jpql = jpql + " join v.organizationSet O where O.id =:oid";
    } else {
        jpql = jpql + " where 1=1";
    }
    if (id >= 0) {
        jpql = jpql + " And v.id =:id";
    }
    if (!vin.equals("")) {
        jpql = jpql + " And v.vin = :vin";
    }
    if (!vendor.equals("")) {
        jpql = jpql + " And v.vendor = :vendor";
    }
    if (!model.equals("")) {
        jpql = jpql + " And v.model = :model";
    }
    if (!displacement.equals("")) {
        jpql = jpql + " And v.displacement = :displacement";
    }
    if (!license_plate.equals("")) {
        jpql = jpql + " And v.license_plate = :license_plate";
    }
    if (t_flag == 0 || t_flag == 1) {
        jpql = jpql + " And v.t_flag =:t_flag";
    }
    if (start_date != null) {
        jpql = jpql + " And v.product_date >= :start_date";
    }
    if (end_date != null) {
        jpql = jpql + " And v.product_date <= :end_date";
    }
    jpql = jpql + " Order by v." + orderByProperty + " " + ascOrDesc;
    jpql_count = jpql;

    TypedQuery query = em.createQuery(jpql, Vehicle.class);
    TypedQuery queryCount = em.createQuery(jpql_count, Vehicle.class);

    if (oid != null && oid >= 0) {
        query.setParameter("oid", oid);
        queryCount.setParameter("oid", oid);
    }
    if (id >= 0) {
        query.setParameter("id", id);
        queryCount.setParameter("id", id);
    }
    if (!vin.equals("")) {
        query.setParameter("vin", vin);
        queryCount.setParameter("vin", vin);
    }
    if (!vendor.equals("")) {
        query.setParameter("vendor", vendor);
        queryCount.setParameter("vendor", vendor);
    }
    if (!model.equals("")) {
        query.setParameter("model", model);
        queryCount.setParameter("model", model);
    }
    if (!displacement.equals("")) {
        query.setParameter("displacement", displacement);
        queryCount.setParameter("displacement", displacement);
    }
    if (!license_plate.equals("")) {
        query.setParameter("license_plate", license_plate);
        queryCount.setParameter("license_plate", license_plate);
    }
    if (t_flag == 0 || t_flag == 1) {
        query.setParameter("t_flag", t_flag);
        queryCount.setParameter("t_flag", t_flag);
    }
    if (start_date != null) {
        query.setParameter("start_date", start_date);
        queryCount.setParameter("start_date", start_date);
    }
    if (end_date != null) {
        query.setParameter("end_date", end_date);
        queryCount.setParameter("end_date", end_date);
    }
    query.setFirstResult((currentPage - 1) * pageSize);
    query.setMaxResults(pageSize);
    List items = query.getResultList();
    Long count = (long) queryCount.getResultList().size();
    return new Page(currentPage, pageSize, count, items);
}

From source file:org.openmeetings.app.data.user.Usermanagement.java

/**
 * query for a list of users// w w w.j  ava  2 s  .c o m
 * 
 * @param users_id
 * @param user_level
 * @param start
 * @param max
 * @param orderby
 * @return
 */
public SearchResult<Users> getUsersList(long user_level, int start, int max, String orderby, boolean asc) {
    try {
        if (authLevelManagement.checkAdminLevel(user_level)) {
            SearchResult<Users> sresult = new SearchResult<Users>();
            sresult.setObjectName(Users.class.getName());
            sresult.setRecords(usersDao.selectMaxFromUsers());

            // get all users
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Users> cq = cb.createQuery(Users.class);
            Root<Users> c = cq.from(Users.class);
            Predicate condition = cb.equal(c.get("deleted"), "false");
            cq.where(condition);
            cq.distinct(asc);
            if (asc) {
                cq.orderBy(cb.asc(c.get(orderby)));
            } else {
                cq.orderBy(cb.desc(c.get(orderby)));
            }
            TypedQuery<Users> q = em.createQuery(cq);
            q.setFirstResult(start);
            q.setMaxResults(max);
            List<Users> ll = q.getResultList();
            sresult.setResult(ll);
            return sresult;
        }
    } catch (Exception ex2) {
        log.error("[getUsersList] " + ex2);
    }
    return null;
}

From source file:org.openmeetings.app.data.user.Usermanagement.java

/**
 * suche eines Bentzers//  ww w  . j a  v a  2 s  .c  o m
 * 
 * @param user_level
 * @param searchstring
 * @param max
 * @param start
 * @return
 */
public List<Users> searchUser(long user_level, String searchcriteria, String searchstring, int max, int start,
        String orderby, boolean asc) {
    if (authLevelManagement.checkAdminLevel(user_level)) {
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Users> cq = cb.createQuery(Users.class);
            Root<Users> c = cq.from(Users.class);
            Expression<String> literal = cb.literal("%" + searchstring + "%");
            // crit.add(Restrictions.ilike(searchcriteria, "%" +
            // searchstring + "%"));
            Path<String> path = c.get(searchcriteria);
            Predicate predicate = cb.like(path, literal);
            Predicate condition = cb.notEqual(c.get("deleted"), "true");
            cq.where(condition, predicate);
            cq.distinct(asc);
            if (asc) {
                cq.orderBy(cb.asc(c.get(orderby)));
            } else {
                cq.orderBy(cb.desc(c.get(orderby)));
            }
            TypedQuery<Users> q = em.createQuery(cq);
            q.setFirstResult(start);
            q.setMaxResults(max);
            List<Users> contactsZ = q.getResultList();
            return contactsZ;
        } catch (Exception ex2) {
            log.error("searchUser", ex2);
        }
    }
    return null;
}

From source file:com.hp.triclops.repository.VehicleRepositoryDAO.java

/**
 * /*from ww w.  j a  v a2 s.c o m*/
 * @param id ?null""??
 * @param vin ?null""??
 * @param vendor ?null""??
 * @param model ?null""??
 * @param t_flag 0 ? 1  ??
 * @param displacement ?null""??
 * @param license_plate ?null""??
 * @param start_date ?null??
 * @param end_date ??null??
 * @param orderByProperty ?? Vehicle?,vin
 * @param ascOrDesc ??? "ASC""DESC"  ???,ASC
 * @param pageSize ??? 0
 * @param currentPage ??? 0
 * @param fuzzy ?
 * @param oid id
 * @return  ????Page
 */
public Page findVehiclesByKeys(Integer id, String vin, String vendor, String model, Integer t_flag,
        String displacement, String license_plate, Date start_date, Date end_date, String orderByProperty,
        String ascOrDesc, Integer pageSize, Integer currentPage, Integer fuzzy, Integer oid) {
    String jpql = "select v FROM Vehicle v";
    String jpql_count = "";
    id = (id == null) ? -1 : id;
    vin = (vin == null) ? "" : EscapeStringUtil.toEscape(vin);
    vendor = (vendor == null) ? "" : vendor;
    model = (model == null) ? "" : model;
    displacement = (displacement == null) ? "" : displacement;
    license_plate = (license_plate == null) ? "" : EscapeStringUtil.toEscape(license_plate);
    orderByProperty = (orderByProperty == null) ? "vin" : orderByProperty;
    ascOrDesc = (ascOrDesc == null) ? "ASC" : ascOrDesc;
    t_flag = (t_flag == null) ? -1 : t_flag;
    pageSize = (pageSize == null) ? 10 : pageSize;
    pageSize = (pageSize <= 0) ? 10 : pageSize;
    currentPage = (currentPage == null) ? 1 : currentPage;
    currentPage = (currentPage <= 0) ? 1 : currentPage;

    if (oid != null && oid >= 0) {
        jpql = jpql + " join v.organizationSet O where O.id =:oid";
    } else {
        jpql = jpql + " where 1=1";
    }
    if (id >= 0) {
        jpql = jpql + " And v.id =:id";
    }
    if (!vin.equals("")) {
        jpql = jpql + " And v.vin like :vin";
    }
    if (!vendor.equals("")) {
        jpql = jpql + " And v.vendor like :vendor";
    }
    if (!model.equals("")) {
        jpql = jpql + " And v.model like :model";
    }
    if (!displacement.equals("")) {
        jpql = jpql + " And v.displacement like :displacement";
    }
    if (!license_plate.equals("")) {
        jpql = jpql + " And v.license_plate like :license_plate";
    }
    if (t_flag == 0 || t_flag == 1) {
        jpql = jpql + " And v.t_flag =:t_flag";
    }
    if (start_date != null) {
        jpql = jpql + " And v.product_date >= :start_date";
    }
    if (end_date != null) {
        jpql = jpql + " And v.product_date <= :end_date";
    }
    jpql = jpql + " Order by v." + orderByProperty + " " + ascOrDesc;
    jpql_count = jpql;

    TypedQuery query = em.createQuery(jpql, Vehicle.class);
    TypedQuery queryCount = em.createQuery(jpql_count, Vehicle.class);
    if (oid != null && oid >= 0) {
        query.setParameter("oid", oid);
        queryCount.setParameter("oid", oid);
    }
    if (id >= 0) {
        query.setParameter("id", id);
        queryCount.setParameter("id", id);
    }
    if (!vin.equals("")) {
        query.setParameter("vin", "%" + vin + "%");
        queryCount.setParameter("vin", "%" + vin + "%");
    }
    if (!vendor.equals("")) {
        query.setParameter("vendor", "%" + vendor + "%");
        queryCount.setParameter("vendor", "%" + vendor + "%");
    }
    if (!model.equals("")) {
        query.setParameter("model", "%" + model + "%");
        queryCount.setParameter("model", "%" + model + "%");
    }
    if (!displacement.equals("")) {
        query.setParameter("displacement", "%" + displacement + "%");
        queryCount.setParameter("displacement", "%" + displacement + "%");
    }
    if (!license_plate.equals("")) {
        query.setParameter("license_plate", "%" + license_plate + "%");
        queryCount.setParameter("license_plate", "%" + license_plate + "%");
    }
    if (t_flag == 0 || t_flag == 1) {
        query.setParameter("t_flag", t_flag);
        queryCount.setParameter("t_flag", t_flag);
    }
    if (start_date != null) {
        query.setParameter("start_date", start_date);
        queryCount.setParameter("start_date", start_date);
    }
    if (end_date != null) {
        query.setParameter("end_date", end_date);
        queryCount.setParameter("end_date", end_date);
    }
    query.setFirstResult((currentPage - 1) * pageSize);
    query.setMaxResults(pageSize);
    List items = query.getResultList();
    Long count = (long) queryCount.getResultList().size();
    return new Page(currentPage, pageSize, count, items);
}

From source file:org.openmeetings.app.data.user.Usermanagement.java

/**
 * @param user_level/*from w ww .  ja  v  a  2 s .c o m*/
 * @param start
 * @param max
 * @param orderby
 * @param asc
 * @param search
 * @return
 */
public SearchResult<Users> getUsersListWithSearch(Long user_level, int start, int max, String orderby,
        boolean asc, String search) {
    try {
        if (authLevelManagement.checkAdminLevel(user_level)) {

            String hql = "select c from Users c " + "where c.deleted = 'false' " + "AND ("
                    + "lower(c.login) LIKE :search " + "OR lower(c.firstname) LIKE :search "
                    + "OR lower(c.lastname) LIKE :search " + ")";

            if (orderby.startsWith("c.")) {
                hql += "ORDER BY " + orderby;
            } else {
                hql += "ORDER BY " + "c." + orderby;
            }

            if (asc) {
                hql += " ASC";
            } else {
                hql += " DESC";
            }

            if (search.length() == 0) {
                search = "%";
            } else {
                search = "%" + search + "%";
            }
            log.debug("getUsersList search: " + search);

            SearchResult<Users> sresult = new SearchResult<Users>();
            sresult.setObjectName(Users.class.getName());
            sresult.setRecords(usersDao.selectMaxFromUsersWithSearch(search));

            // get all users
            TypedQuery<Users> query = em.createQuery(hql, Users.class);
            query.setParameter("search", StringUtils.lowerCase(search));
            query.setMaxResults(max);
            query.setFirstResult(start);

            sresult.setResult(query.getResultList());

            return sresult;
        }
    } catch (Exception ex2) {
        log.error("[getUsersList] " + ex2);
    }
    return null;
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public List<com.enioka.jqm.api.JobInstance> getJobs(Query query) {
    if ((query.getFirstRow() != null || query.getPageSize() != null) && query.isQueryLiveInstances()
            && query.isQueryHistoryInstances()) {
        throw new JqmInvalidRequestException("cannot use paging on live instances");
    }//from   w  w w  .j  a v  a 2 s . co  m
    if (query.isQueryLiveInstances() && query.isQueryHistoryInstances() && query.getSorts().size() > 0) {
        throw new JqmInvalidRequestException(
                "cannot use sorting when querying both live and historical instances");
    }

    EntityManager em = null;
    try {
        em = getEm();

        // Not using CriteriaBuilder - too much hassle for too little benefit
        String wh = "";
        Map<String, Object> prms = new HashMap<String, Object>();

        // String predicates
        wh += getStringPredicate("userName", query.getUser(), prms);
        wh += getStringPredicate("sessionId", query.getSessionId(), prms);
        wh += getStringPredicate("instanceKeyword1", query.getInstanceKeyword1(), prms);
        wh += getStringPredicate("instanceKeyword2", query.getInstanceKeyword2(), prms);
        wh += getStringPredicate("instanceKeyword3", query.getInstanceKeyword3(), prms);
        wh += getStringPredicate("instanceModule", query.getInstanceModule(), prms);
        wh += getStringPredicate("instanceApplication", query.getInstanceApplication(), prms);

        // Integer
        wh += getIntPredicate("parentId", query.getParentId(), prms);
        wh += getIntPredicate("id", query.getJobInstanceId(), prms);
        wh += getIntPredicate("queue.id", query.getQueueId() == null ? null : query.getQueueId(), prms);

        // Now, run queries...
        List<com.enioka.jqm.api.JobInstance> res2 = new ArrayList<com.enioka.jqm.api.JobInstance>();

        // ////////////////////////////////////////
        // Job Instance query
        if (query.isQueryLiveInstances()) {
            // Sort
            String sort = "";
            for (SortSpec s : query.getSorts()) {
                sort += s.col.getJiField() == null ? ""
                        : ",h." + s.col.getJiField() + " "
                                + (s.order == Query.SortOrder.ASCENDING ? "ASC" : "DESC");
            }
            if (sort.isEmpty()) {
                sort = " ORDER BY h.id";
            } else {
                sort = " ORDER BY " + sort.substring(1);
            }

            // Finish query string
            String wh2 = "" + wh;
            Map<String, Object> prms2 = new HashMap<String, Object>();
            prms2.putAll(prms);
            wh2 += getStringPredicate("queue.name", query.getQueueName(), prms2);

            // tag fields should be looked for in linked object for active JI
            wh2 += getStringPredicate("jd.applicationName", query.getApplicationName(), prms2);
            wh2 += getStringPredicate("jd.keyword1", query.getJobDefKeyword1(), prms2);
            wh2 += getStringPredicate("jd.keyword2", query.getJobDefKeyword2(), prms2);
            wh2 += getStringPredicate("jd.keyword3", query.getJobDefKeyword3(), prms2);
            wh2 += getStringPredicate("jd.module", query.getJobDefModule(), prms2);
            wh2 += getStringPredicate("jd.application", query.getJobDefApplication(), prms2);
            wh2 += getStringPredicate("node.name", query.getNodeName(), prms2);

            // Calendar fields are specific (no common fields between History and JobInstance)
            wh2 += getCalendarPredicate("creationDate", query.getEnqueuedAfter(), ">=", prms2);
            wh2 += getCalendarPredicate("creationDate", query.getEnqueuedBefore(), "<=", prms2);
            wh2 += getCalendarPredicate("executionDate", query.getBeganRunningAfter(), ">=", prms2);
            wh2 += getCalendarPredicate("executionDate", query.getBeganRunningBefore(), "<=", prms2);
            wh2 += getStatusPredicate("state", query.getStatus(), prms2);
            if (wh2.length() >= 3) {
                wh2 = " WHERE " + wh2.substring(3);
            }

            TypedQuery<JobInstance> q2 = em.createQuery(
                    "SELECT h FROM JobInstance h LEFT JOIN FETCH h.jd LEFT JOIN FETCH h.node " + wh2 + sort,
                    JobInstance.class);
            for (Map.Entry<String, Object> entry : prms2.entrySet()) {
                q2.setParameter(entry.getKey(), entry.getValue());
            }
            if (query.getFirstRow() != null) {
                q2.setFirstResult(query.getFirstRow());
            }
            if (query.getPageSize() != null) {
                q2.setMaxResults(query.getPageSize());
            }
            if (query.getFirstRow() != null || query.getPageSize() != null) {
                TypedQuery<Long> qCount = em.createQuery("SELECT COUNT(h) FROM JobInstance h " + wh2,
                        Long.class);
                for (Map.Entry<String, Object> entry : prms2.entrySet()) {
                    qCount.setParameter(entry.getKey(), entry.getValue());
                }
                query.setResultSize(new BigDecimal(qCount.getSingleResult()).intValueExact());
            }

            for (JobInstance ji : q2.getResultList()) {
                res2.add(getJob(ji, em));
            }
        }

        // ////////////////////////////////////////
        // History query
        if (query.isQueryHistoryInstances()) {
            wh += getStringPredicate("queueName", query.getQueueName(), prms);

            // tag fields should be looked directly in the denormalized fields for history.
            wh += getStringPredicate("applicationName", query.getApplicationName(), prms);
            wh += getStringPredicate("keyword1", query.getJobDefKeyword1(), prms);
            wh += getStringPredicate("keyword2", query.getJobDefKeyword2(), prms);
            wh += getStringPredicate("keyword3", query.getJobDefKeyword3(), prms);
            wh += getStringPredicate("module", query.getJobDefModule(), prms);
            wh += getStringPredicate("application", query.getJobDefApplication(), prms);
            wh += getStringPredicate("nodeName", query.getNodeName(), prms);

            // Calendar fields are specific (no common fields between History and JobInstance)
            wh += getCalendarPredicate("enqueueDate", query.getEnqueuedAfter(), ">=", prms);
            wh += getCalendarPredicate("enqueueDate", query.getEnqueuedBefore(), "<=", prms);
            wh += getCalendarPredicate("executionDate", query.getBeganRunningAfter(), ">=", prms);
            wh += getCalendarPredicate("executionDate", query.getBeganRunningBefore(), "<=", prms);
            wh += getCalendarPredicate("endDate", query.getEndedAfter(), ">=", prms);
            wh += getCalendarPredicate("endDate", query.getEndedBefore(), "<=", prms);
            wh += getStatusPredicate("status", query.getStatus(), prms);
            if (wh.length() >= 3) {
                wh = " WHERE " + wh.substring(3);
            }

            // Order by
            String sort = "";
            for (SortSpec s : query.getSorts()) {
                sort += ",h." + s.col.getHistoryField() + " "
                        + (s.order == Query.SortOrder.ASCENDING ? "ASC" : "DESC");
            }
            if (sort.isEmpty()) {
                sort = " ORDER BY h.id";
            } else {
                sort = " ORDER BY " + sort.substring(1);
            }

            TypedQuery<History> q1 = em.createQuery(
                    "SELECT h FROM History h LEFT JOIN FETCH h.jd LEFT JOIN FETCH h.node LEFT JOIN FETCH h.queue "
                            + wh + sort,
                    History.class);
            for (Map.Entry<String, Object> entry : prms.entrySet()) {
                q1.setParameter(entry.getKey(), entry.getValue());
            }
            if (query.getFirstRow() != null) {
                q1.setFirstResult(query.getFirstRow());
            }
            if (query.getPageSize() != null) {
                q1.setMaxResults(query.getPageSize());
            }
            if (query.getFirstRow() != null || query.getPageSize() != null) {
                TypedQuery<Long> qCount = em.createQuery("SELECT COUNT(h) FROM History h " + wh, Long.class);
                for (Map.Entry<String, Object> entry : prms.entrySet()) {
                    qCount.setParameter(entry.getKey(), entry.getValue());
                }
                query.setResultSize(new BigDecimal(qCount.getSingleResult()).intValueExact());
            }

            // Optimization: fetch messages and parameters in one go.
            List<History> results = q1.getResultList();
            List<Integer> ids = new ArrayList<Integer>();
            for (History ji : results) {
                ids.add(ji.getId());
            }
            if (!ids.isEmpty()) {
                List<RuntimeParameter> rps = em
                        .createQuery("SELECT rp FROM RuntimeParameter rp WHERE rp.ji IN (:p)",
                                RuntimeParameter.class)
                        .setParameter("p", ids).getResultList();
                List<Message> msgs = em
                        .createQuery("SELECT rp FROM Message rp WHERE rp.ji IN (:p)", Message.class)
                        .setParameter("p", ids).getResultList();

                for (History ji : results) {
                    res2.add(getJob(ji, em, rps, msgs));
                }
            }
        }

        query.setResults(res2);
        return res2;
    } catch (Exception e) {
        throw new JqmClientException("an error occured during query execution", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:org.openmeetings.app.data.user.Usermanagement.java

public SearchResult<Users> getAllUserByRange(String search, int start, int max, String orderby, boolean asc) {
    try {// w w  w . j  a  v a  2s  .  co  m
        SearchResult<Users> sresult = new SearchResult<Users>();
        sresult.setObjectName(Users.class.getName());
        sresult.setRecords(usersDao.getAllUserMax(search));

        String[] searchItems = search.split(" ");

        log.debug("getUserContactsBySearch: " + search);
        // log.debug("getUserContactsBySearch: "+ userId);

        String hql = "select u from  Users u " + "WHERE u.deleted = 'false' ";

        hql += "AND ( ";
        for (int i = 0; i < searchItems.length; i++) {
            if (i != 0) {
                hql += " OR ";
            }
            hql += "( " + "lower(u.lastname) LIKE '" + StringUtils.lowerCase("%" + searchItems[i] + "%") + "' "
                    + "OR lower(u.firstname) LIKE '" + StringUtils.lowerCase("%" + searchItems[i] + "%") + "' "
                    + "OR lower(u.login) LIKE '" + StringUtils.lowerCase("%" + searchItems[i] + "%") + "' "
                    + "OR lower(u.adresses.email) LIKE '" + StringUtils.lowerCase("%" + searchItems[i] + "%")
                    + "' " + ") ";

        }

        hql += " ) ";
        if (orderby != null && orderby.length() > 0) {
            hql += "ORDER BY " + orderby;
        }

        if (asc) {
            hql += " ASC ";
        } else {
            hql += " DESC ";
        }

        log.debug("Show HQL: " + hql);

        TypedQuery<Users> query = em.createQuery(hql, Users.class);
        // query.setParameter("macomUserId", userId);

        // query
        // if (asc) ((Criteria) query).addOrder(Order.asc(orderby));
        // else ((Criteria) query).addOrder(Order.desc(orderby));
        query.setFirstResult(start);
        query.setMaxResults(max);
        List<Users> ll = query.getResultList();

        sresult.setResult(ll);

        return sresult;

    } catch (Exception ex2) {
        log.error("[getAllUserByRange] ", ex2);
        ex2.printStackTrace();
    }
    return null;
}

From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

@Override
public IBundleProvider history(final IdDt theId, final Date theSince) {
    final InstantDt end = createHistoryToTimestamp();
    final String resourceType = getContext().getResourceDefinition(myResourceType).getName();

    T currentTmp;/*from   w  w w  . ja v a 2 s  .  c o m*/
    try {
        BaseHasResource entity = readEntity(theId.toVersionless(), false);
        validateResourceType(entity);
        currentTmp = toResource(myResourceType, entity);
        if (ResourceMetadataKeyEnum.UPDATED.get(currentTmp).after(end.getValue())) {
            currentTmp = null;
        }
    } catch (ResourceNotFoundException e) {
        currentTmp = null;
    }

    final T current = currentTmp;

    String querySring = "SELECT count(h) FROM ResourceHistoryTable h "
            + "WHERE h.myResourceId = :PID AND h.myResourceType = :RESTYPE" + " AND h.myUpdated < :END"
            + (theSince != null ? " AND h.myUpdated >= :SINCE" : "");
    TypedQuery<Long> countQuery = myEntityManager.createQuery(querySring, Long.class);
    countQuery.setParameter("PID", translateForcedIdToPid(theId));
    countQuery.setParameter("RESTYPE", resourceType);
    countQuery.setParameter("END", end.getValue(), TemporalType.TIMESTAMP);
    if (theSince != null) {
        countQuery.setParameter("SINCE", theSince, TemporalType.TIMESTAMP);
    }
    int historyCount = countQuery.getSingleResult().intValue();

    final int offset;
    final int count;
    if (current != null) {
        count = historyCount + 1;
        offset = 1;
    } else {
        offset = 0;
        count = historyCount;
    }

    if (count == 0) {
        throw new ResourceNotFoundException(theId);
    }

    return new IBundleProvider() {

        @Override
        public InstantDt getPublished() {
            return end;
        }

        @Override
        public List<IResource> getResources(int theFromIndex, int theToIndex) {
            ArrayList<IResource> retVal = new ArrayList<IResource>();
            if (theFromIndex == 0 && current != null) {
                retVal.add(current);
            }

            TypedQuery<ResourceHistoryTable> q = myEntityManager.createQuery(
                    "SELECT h FROM ResourceHistoryTable h WHERE h.myResourceId = :PID AND h.myResourceType = :RESTYPE AND h.myUpdated < :END "
                            + (theSince != null ? " AND h.myUpdated >= :SINCE" : "")
                            + " ORDER BY h.myUpdated ASC",
                    ResourceHistoryTable.class);
            q.setParameter("PID", translateForcedIdToPid(theId));
            q.setParameter("RESTYPE", resourceType);
            q.setParameter("END", end.getValue(), TemporalType.TIMESTAMP);
            if (theSince != null) {
                q.setParameter("SINCE", theSince, TemporalType.TIMESTAMP);
            }

            int firstResult = Math.max(0, theFromIndex - offset);
            q.setFirstResult(firstResult);

            int maxResults = (theToIndex - theFromIndex) + 1;
            q.setMaxResults(maxResults);

            List<ResourceHistoryTable> results = q.getResultList();
            for (ResourceHistoryTable next : results) {
                if (retVal.size() == maxResults) {
                    break;
                }
                retVal.add(toResource(myResourceType, next));
            }

            return retVal;
        }

        @Override
        public Integer preferredPageSize() {
            return null;
        }

        @Override
        public int size() {
            return count;
        }
    };

}