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.user.dao.PrivateMessagesDaoImpl.java

public List<PrivateMessages> getPrivateMessagesByUser(Long toUserId, String search, String orderBy, int start,
        Boolean asc, Long privateMessageFolderId, int max) {
    try {//from  ww w.  j a v  a 2 s  .c om

        String hql = "select c from PrivateMessages c " + "where c.to.user_id = :toUserId "
                + "AND c.isTrash = :isTrash " + "AND c.owner.user_id = :toUserId "
                + "AND c.privateMessageFolderId = :privateMessageFolderId ";

        if (search.length() != 0) {
            hql += "AND ( ";
            hql += "lower(c.subject) LIKE :search ";
            hql += "OR lower(c.message) LIKE :search ";
            hql += "OR lower(c.from.firstname) LIKE :search ";
            hql += "OR lower(c.from.lastname) LIKE :search ";
            hql += "OR lower(c.from.login) LIKE :search ";
            hql += "OR lower(c.from.adresses.email) LIKE :search ";
            hql += " ) ";
        }

        hql += "ORDER BY " + orderBy;

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

        TypedQuery<PrivateMessages> query = em.createQuery(hql, PrivateMessages.class);
        query.setParameter("toUserId", toUserId);
        query.setParameter("isTrash", false);
        query.setParameter("privateMessageFolderId", privateMessageFolderId);
        if (search.length() != 0) {
            query.setParameter("search", StringUtils.lowerCase("%" + search + "%"));
        }
        query.setFirstResult(start);
        query.setMaxResults(max);
        List<PrivateMessages> ll = query.getResultList();

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

From source file:org.openmeetings.app.data.user.dao.PrivateMessagesDaoImpl.java

public List<PrivateMessages> getFolderPrivateMessagesByUser(Long toUserId, String search, String orderBy,
        int start, Boolean asc, Long privateMessageFolderId, int max) {
    try {// ww w . j  av  a2s  . c o  m

        String hql = "select c from PrivateMessages c " + "where c.isTrash = :isTrash "
                + "AND c.owner.user_id = :toUserId "
                + "AND c.privateMessageFolderId = :privateMessageFolderId ";

        if (search.length() != 0) {
            hql += "AND ( ";
            hql += "lower(c.subject) LIKE :search ";
            hql += "OR lower(c.message) LIKE :search ";
            hql += "OR lower(c.from.firstname) LIKE :search ";
            hql += "OR lower(c.from.lastname) LIKE :search ";
            hql += "OR lower(c.from.login) LIKE :search ";
            hql += "OR lower(c.from.adresses.email) LIKE :search ";
            hql += " ) ";
        }

        hql += "ORDER BY " + orderBy;

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

        log.debug("HQL " + hql);

        log.debug("privateMessageFolderId " + privateMessageFolderId);

        TypedQuery<PrivateMessages> query = em.createQuery(hql, PrivateMessages.class);
        query.setParameter("toUserId", toUserId);
        query.setParameter("isTrash", false);
        query.setParameter("privateMessageFolderId", privateMessageFolderId);
        if (search.length() != 0) {
            query.setParameter("search", StringUtils.lowerCase("%" + search + "%"));
        }
        query.setFirstResult(start);
        query.setMaxResults(max);
        List<PrivateMessages> ll = query.getResultList();

        return ll;

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

From source file:com.deloitte.smt.service.SignalDetectionService.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public SmtResponse findAllForSearch(SearchDto searchDto) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();

    Root<SignalDetection> rootSignalDetection = criteriaQuery.from(SignalDetection.class);
    Join<SignalDetection, TopicSignalDetectionAssignmentAssignees> joinDetectionAssignees = rootSignalDetection
            .join("topicSignalDetectionAssignmentAssignees", JoinType.LEFT); //left outer join

    if (null != searchDto) {
        Root<Ingredient> rootIngredient = criteriaQuery.from(Ingredient.class);
        List<Predicate> predicates = new ArrayList<>(10);
        predicates.add(criteriaBuilder.equal(rootSignalDetection.get("id"),
                rootIngredient.get(SmtConstant.DETECTION_ID.getDescription())));

        addDescription(searchDto, criteriaBuilder, rootSignalDetection, predicates);
        addFrequency(searchDto, criteriaBuilder, rootSignalDetection, predicates);
        addIngredients(searchDto, criteriaBuilder, rootIngredient, predicates);
        addProducts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addLicenses(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addSocs(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addHlts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addHlgts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addPts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addCreatedOrLastRunDate(searchDto, criteriaBuilder, rootSignalDetection, predicates);
        /**TopicSignalValidationAssignmentAssignees **/
        addUserGroupKeys(searchDto, criteriaBuilder, joinDetectionAssignees, rootSignalDetection, predicates);

        Predicate andPredicate = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        criteriaQuery.multiselect(rootSignalDetection).where(andPredicate)
                .orderBy(criteriaBuilder
                        .desc(rootSignalDetection.get(SmtConstant.CREATED_DATE.getDescription())))
                .distinct(true);/*from  www  . ja va  2s  .  c om*/

    } else {
        criteriaQuery.multiselect(rootSignalDetection)
                .orderBy(criteriaBuilder
                        .desc(rootSignalDetection.get(SmtConstant.CREATED_DATE.getDescription())))
                .distinct(true);
    }
    SmtResponse smtResponse = new SmtResponse();
    TypedQuery<SignalDetection> q = entityManager.createQuery(criteriaQuery);
    if (!CollectionUtils.isEmpty(q.getResultList())) {
        smtResponse.setTotalRecords(q.getResultList().size());
    }
    if (searchDto != null && searchDto.getFetchSize() != 0) {
        q.setFirstResult(searchDto.getFromRecord());
        q.setMaxResults(searchDto.getFetchSize());
        smtResponse.setFetchSize(searchDto.getFetchSize());
        smtResponse.setFromRecord(searchDto.getFromRecord());
    }
    smtResponse.setResult(q.getResultList());

    if (!CollectionUtils.isEmpty(smtResponse.getResult())) {
        List<SignalDetection> result = (List<SignalDetection>) smtResponse.getResult();
        for (SignalDetection signalDetection : result) {
            signalDetection.setDenominatorForPoisson(
                    denominatorForPoissonRepository.findByDetectionId(signalDetection.getId()));
        }
    }
    return smtResponse;
}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> List<T> findBy(Class<T> clazz, JPAEntityFilter<T> filter) throws Exception {
    List<T> res = new ArrayList<T>();

    testClazz(clazz);/*  w ww  .ja  v  a 2s  . c  o m*/

    EntityManager em = getEntityManager();

    try {

        if (filter != null) {
            CriteriaQuery<T> cq = filter.getCriteria(clazz, getEmf());
            TypedQuery<T> q = em.createQuery(cq);

            q.setFirstResult(filter.getLimit() * filter.getPageNumber());
            q.setMaxResults(filter.getLimit());

            res = q.getResultList();
        } else {
            res = findAll(clazz);
        }

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            // if (em.getTransaction().isActive())
            // em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

    return res;
}

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TAzCarinfoEntity> listAllCandidateCars(String[] applicationIds, String keyword, Integer offset,
        Integer limit, PrincipalExt principalExt) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TAzCarinfoEntity> cq = cb.createQuery(TAzCarinfoEntity.class);
    Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class);
    carRoot.fetch(TAzCarinfoEntity_.driver, JoinType.LEFT);

    cq.select(carRoot);//  www  . ja  v  a  2  s  .co  m
    Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class);

    applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, null, cb,
            principalExt);
    Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.clzt), "02"),
            cb.or(cb.equal(carRoot.get(TAzCarinfoEntity_.repairingState), RepairingState.NONE.id()),
                    cb.isNull(carRoot.get(TAzCarinfoEntity_.repairingState))

            ), cb.not(cb.exists(overlapScheduleCarSubQuery))

    );

    if (keyword != null) {
        predicate = cb.and(predicate,
                cb.or(cb.like(carRoot.get(TAzCarinfoEntity_.sysOrg).get(TSysOrgEntity_.orgname),
                        "%" + keyword + "%"),
                        cb.like(carRoot.get(TAzCarinfoEntity_.cphm), "%" + keyword + "%")));
    }

    cq.where(predicate);
    cq.orderBy(cb.asc(carRoot.get(TAzCarinfoEntity_.cphm)));
    TypedQuery<TAzCarinfoEntity> query = em.createQuery(cq);
    if (offset != null) {
        query.setFirstResult(offset);
    }

    if (limit != null) {
        query.setMaxResults(limit);
    }

    applySecurityFilter("cars", principalExt);

    return query.getResultList();
}

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TRsDriverinfoEntity> listAllCandidateDrivers(String[] applicationIds, String carId, String keyword,
        Integer offset, Integer limit, PrincipalExt principalExt) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TRsDriverinfoEntity> cq = cb.createQuery(TRsDriverinfoEntity.class);
    Root<TRsDriverinfoEntity> driverRoot = cq.from(TRsDriverinfoEntity.class);
    Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class);
    cq.select(driverRoot);/*from  w w  w  .  j  a  v a 2  s . co m*/

    Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class);

    applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, driverRoot, cb,
            principalExt);

    Subquery<TRsDriverinfoEntity> subqueryLicense = cq.subquery(TRsDriverinfoEntity.class);
    Root<TAzJzRelaEntity> licenseMapping = subqueryLicense.from(TAzJzRelaEntity.class);
    subqueryLicense.select(driverRoot);
    subqueryLicense.where(

            cb.equal(carRoot.get(TAzCarinfoEntity_.xszcx), licenseMapping.get(TAzJzRelaEntity_.xszcx)),
            cb.equal(licenseMapping.get(TAzJzRelaEntity_.jzyq),
                    driverRoot.get(TRsDriverinfoEntity_.drivecartype)));

    Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.id), carId),
            cb.equal(driverRoot.get(TRsDriverinfoEntity_.department), carRoot.get(TAzCarinfoEntity_.sysOrg)),
            cb.equal(driverRoot.get(TRsDriverinfoEntity_.enabled), "1"),
            cb.or(cb.exists(subqueryLicense), cb.isNull(driverRoot.get(TRsDriverinfoEntity_.drivecartype))

            ),

            cb.not(cb.exists(overlapScheduleCarSubQuery))

    );

    if (keyword != null) {
        predicate = cb.and(predicate,
                cb.or(cb.like(driverRoot.get(TRsDriverinfoEntity_.drivername), "%" + keyword + "%")));
    }

    cq.where(predicate);
    cq.orderBy(cb
            .asc(cb.function("casttogbk", String.class, cb.trim(driverRoot.get(TRsDriverinfoEntity_.drivername))

    )));
    TypedQuery<TRsDriverinfoEntity> query = em.createQuery(cq);
    if (offset != null) {
        query.setFirstResult(offset);
    }

    if (limit != null) {
        query.setMaxResults(limit);
    }

    return query.getResultList();

}

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TBusApplyinfoEntity> getAllApplications(String coordinatorUserId, String reasonType, String status,
        DateTime startBefore, DateTime startAfter, DateTime endBefore, DateTime endAfter, Integer offset,
        Integer limit, OrderByParam orderByParam, PrincipalExt principalExt) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    applyRoot.fetch(TBusApplyinfoEntity_.passenger);
    Fetch<TBusApplyinfoEntity, TSysUserEntity> fetchCoordinator = applyRoot
            .fetch(TBusApplyinfoEntity_.coordinator);
    applyRoot.fetch(TBusApplyinfoEntity_.department);
    Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot
            .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.senduser, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.reciveuser, JoinType.LEFT);
    Fetch<TBusScheduleRelaEntity, TBusScheduleCarEntity> fetchScheduleCar = scheduleFetch
            .fetch(TBusScheduleRelaEntity_.scheduleCars, JoinType.LEFT);
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.car, JoinType.LEFT).fetch(TAzCarinfoEntity_.depot,
            JoinType.LEFT);/*from ww  w  .jav a 2s.c o m*/
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.driver, JoinType.LEFT).fetch(TRsDriverinfoEntity_.department,
            JoinType.LEFT);
    Predicate predicate = cb.conjunction();
    if (coordinatorUserId != null) {
        Join<TBusApplyinfoEntity, TSysUserEntity> joinCoordinator = (Join<TBusApplyinfoEntity, TSysUserEntity>) fetchCoordinator;
        predicate = cb.and(predicate, cb.equal(joinCoordinator.get(TSysUserEntity_.userid), coordinatorUserId));
    }
    if (reasonType != null) {
        predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.reason), reasonType));
    }
    if (status != null) {
        if (status.indexOf(":") < 0) {
            predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.status), status));
        } else {
            String[] statusList = status.split(":");
            predicate = cb.and(predicate,
                    applyRoot.get(TBusApplyinfoEntity_.status).in(Arrays.asList(statusList)));
        }
    }

    if (startBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startBefore));
    }

    if (startAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startAfter));
    }

    if (endBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endBefore));
    }

    if (endAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endAfter));
    }

    cq.where(predicate);

    List<Order> orders = new ArrayList<>();
    if (orderByParam != null) {
        for (OrderByParam.OrderBy orderBy : orderByParam.getOrderBies()) {
            Order order = null;
            if (orderBy.getFiled().toLowerCase().equals("start".toLowerCase())) {
                order = cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime));
            }
            if (order != null && !orderBy.isAsc()) {
                order = order.reverse();
            }
            if (order != null) {
                orders.add(order);
            }
        }

    }
    if (orders.size() == 0) {
        cq.orderBy(cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime)));
    } else {
        cq.orderBy(orders);
    }

    TypedQuery<TBusApplyinfoEntity> query = em.createQuery(cq);

    if (offset != null) {
        query.setFirstResult(offset);
    }
    if (limit != null) {
        query.setMaxResults(limit);
    }

    applySecurityFilter("applications", principalExt);

    return query.getResultList();
}

From source file:org.jdal.dao.jpa.JpaDao.java

/**
 * {@inheritDoc}//w w w  . j  a  va 2s  .  c om
 */
public List<Serializable> getKeys(Page<T> page) {
    Filter filter = null;
    TypedQuery<Serializable> query = null;
    SingularAttribute<? super T, ?> id = getIdAttribute();
    // try named query
    if (page.getFilter() instanceof Filter) {
        filter = (Filter) page.getFilter();
        String queryString = getQueryString(filter.getFilterName());
        if (queryString != null) {
            String keyQuery = JpaUtils.getKeyQuery(queryString, id.getName());
            // add Order
            if (page.getSortName() != null)
                keyQuery = JpaUtils.addOrder(keyQuery, page.getSortName(), page.getOrder() == Page.Order.ASC);

            query = em.createQuery(keyQuery, Serializable.class);
            applyFilter(query, filter);
        } else {
            query = getKeyCriteriaQuery(id, page);
        }
    } else {
        query = getKeyCriteriaQuery(id, page);
    }

    query.setFirstResult(page.getStartIndex());
    query.setMaxResults(page.getPageSize());

    return query.getResultList();
}

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

/**
 * gets a list of all availible rooms/*from   w  ww . j ava 2  s .  c o  m*/
 * 
 * @param user_level
 * @param start
 * @param max
 * @param orderby
 * @param asc
 * @return
 */
public List<Rooms> getRoomsInternatl(int start, int max, String orderby, boolean asc) {
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Rooms> cq = cb.createQuery(Rooms.class);
        Root<Rooms> c = cq.from(Rooms.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<Rooms> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Rooms> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getRooms ] ", ex2);
    }
    return null;
}

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

public List<Rooms> getRoomsInternatlbyType(int start, int max, String orderby, boolean asc,
        String externalRoomType) {
    try {//from ww  w . ja  va2 s.c om
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Rooms> cq = cb.createQuery(Rooms.class);
        Root<Rooms> c = cq.from(Rooms.class);
        Predicate condition = cb.equal(c.get("deleted"), "false");
        Predicate subCondition = cb.equal(c.get("externalRoomType"), externalRoomType);
        cq.where(condition, subCondition);
        cq.distinct(asc);
        if (asc) {
            cq.orderBy(cb.asc(c.get(orderby)));
        } else {
            cq.orderBy(cb.desc(c.get(orderby)));
        }
        TypedQuery<Rooms> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Rooms> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getRooms ] ", ex2);
    }
    return null;
}