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:gov.osti.services.Metadata.java

/**
 * Acquire a List of records in pending ("Submitted") state, to be approved
 * for indexing and searching.// ww w.j  ava2 s  . c o m
 *
 * JSON response is of the form:
 *
 * {"records":[{"code_id":n, ...} ],
 *  "start":0, "rows":20, "total":100}
 *
 * Where records is an array of DOECodeMetadata JSON, start is the beginning
 * row number, rows is the number requested (or total if less available),
 * and total is the total number of rows matching the filter.
 *
 * Return Codes:
 * 200 - OK, JSON is returned as above
 * 401 - Unauthorized, login is required
 * 403 - Forbidden, insufficient privileges (role required)
 * 500 - unexpected error
 *
 * @param start the starting row number (from 0)
 * @param rows number of rows desired (0 is unlimited)
 * @param siteCode (optional) a SITE OWNERSHIP CODE to filter by site
 * @param state the WORKFLOW STATE if desired (default Submitted and Announced). One of
 * Approved, Saved, Submitted, or Announced, if supplied.
 * @return JSON of a records response
 */
@GET
@Path("/projects/pending")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
@RequiresRoles("OSTI")
public Response listProjectsPending(@QueryParam("start") int start, @QueryParam("rows") int rows,
        @QueryParam("site") String siteCode, @QueryParam("state") String state) {
    EntityManager em = DoeServletContextListener.createEntityManager();

    try {
        // get a JPA CriteriaBuilder instance
        CriteriaBuilder cb = em.getCriteriaBuilder();
        // create a CriteriaQuery for the COUNT
        CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
        Root<DOECodeMetadata> md = countQuery.from(DOECodeMetadata.class);
        countQuery.select(cb.count(md));

        Expression<String> workflowStatus = md.get("workflowStatus");
        Expression<String> siteOwnershipCode = md.get("siteOwnershipCode");

        // default requested STATE; take Submitted and Announced as the default values if not supplied
        List<DOECodeMetadata.Status> requestedStates = new ArrayList();
        String queryState = (StringUtils.isEmpty(state)) ? "" : state.toLowerCase();
        switch (queryState) {
        case "approved":
            requestedStates.add(DOECodeMetadata.Status.Approved);
            break;
        case "saved":
            requestedStates.add(DOECodeMetadata.Status.Saved);
            break;
        case "submitted":
            requestedStates.add(DOECodeMetadata.Status.Submitted);
            break;
        case "announced":
            requestedStates.add(DOECodeMetadata.Status.Announced);
            break;
        default:
            requestedStates.add(DOECodeMetadata.Status.Submitted);
            requestedStates.add(DOECodeMetadata.Status.Announced);
            break;
        }

        Predicate statusPredicate = workflowStatus.in(requestedStates);
        ParameterExpression<String> site = cb.parameter(String.class, "site");

        if (null == siteCode) {
            countQuery.where(statusPredicate);
        } else {
            countQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site)));
        }
        // query for the COUNT
        TypedQuery<Long> cq = em.createQuery(countQuery);
        cq.setParameter("status", requestedStates);
        if (null != siteCode)
            cq.setParameter("site", siteCode);

        long rowCount = cq.getSingleResult();
        // rows count should be less than 100 for pagination; 0 is a special case
        rows = (rows > 100) ? 100 : rows;

        // create a CriteriaQuery for the ROWS
        CriteriaQuery<DOECodeMetadata> rowQuery = cb.createQuery(DOECodeMetadata.class);
        rowQuery.select(md);

        if (null == siteCode) {
            rowQuery.where(statusPredicate);
        } else {
            rowQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site)));
        }

        TypedQuery<DOECodeMetadata> rq = em.createQuery(rowQuery);
        rq.setParameter("status", requestedStates);
        if (null != siteCode)
            rq.setParameter("site", siteCode);
        rq.setFirstResult(start);
        if (0 != rows)
            rq.setMaxResults(rows);

        RecordsList records = new RecordsList(rq.getResultList());
        records.setTotal(rowCount);
        records.setStart(start);

        return Response.ok().entity(mapper.valueToTree(records).toString()).build();
    } finally {
        em.close();
    }
}

From source file:gov.gtas.repository.CaseDispositionRepositoryImpl.java

@Override
public Pair<Long, List<Case>> findByCriteria(CaseRequestDto dto) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Case> q = cb.createQuery(Case.class);
    Root<Case> root = q.from(Case.class);
    List<Predicate> predicates = new ArrayList<>();

    TypedQuery<Case> typedQuery = em.createQuery(q);

    // sorting//from  w  w  w  .jav  a  2 s.co m
    if (dto.getSort() != null) {
        List<Order> orders = new ArrayList<>();
        for (SortOptionsDto sort : dto.getSort()) {
            Expression<?> e = root.get(sort.getColumn());
            Order order;
            if ("desc".equalsIgnoreCase(sort.getDir())) {
                order = cb.desc(e);
            } else {
                order = cb.asc(e);
            }
            orders.add(order);
        }
        q.orderBy(orders);
    }

    if (dto.getFlightId() != null) {
        predicates.add(cb.equal(root.<Long>get("flightId"), dto.getFlightId()));
    }

    if (dto.getPaxId() != null) {
        predicates.add(cb.equal(root.<Long>get("paxId"), dto.getPaxId()));
    }

    if (dto.getPaxName() != null) {
        String likeString = String.format("%%%s%%", dto.getPaxName().toUpperCase());
        predicates.add(cb.like(root.<String>get("paxName"), likeString));
    }

    if (dto.getLastName() != null) { // map this to full pax name
        String likeString = String.format("%%%s%%", dto.getLastName().toUpperCase());
        predicates.add(cb.like(root.<String>get("paxName"), likeString));
    }

    if (dto.getStatus() != null) {
        String likeString = String.format("%%%s%%", dto.getStatus().toUpperCase());
        predicates.add(cb.like(root.<String>get("status"), likeString));
    }

    if (dto.getFlightNumber() != null) {
        predicates.add(cb.equal(root.<Long>get("flightNumber"), dto.getFlightNumber()));
    }

    if (dto.getRuleCatId() != null) {
        predicates.add(cb.equal(root.<Long>get("highPriorityRuleCatId"), dto.getRuleCatId()));
    }

    Predicate etaCondition;
    if (dto.getEtaStart() != null && dto.getEtaEnd() != null) {

        Path<Date> eta = root.<Date>get("flightETADate");
        Predicate startPredicate = cb.or(cb.isNull(eta), cb.greaterThanOrEqualTo(eta, dto.getEtaStart()));
        Predicate endPredicate = cb.or(cb.isNull(eta), cb.lessThanOrEqualTo(eta, dto.getEtaEnd()));
        etaCondition = cb.and(startPredicate, endPredicate);
        predicates.add(etaCondition);
    }

    q.select(root).where(predicates.toArray(new Predicate[] {}));
    typedQuery = em.createQuery(q);

    // total count
    CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    countQuery.select(cb.count(countQuery.from(Case.class))).where(predicates.toArray(new Predicate[] {}));
    Long count = em.createQuery(countQuery).getSingleResult();

    // pagination
    int pageNumber = dto.getPageNumber();
    int pageSize = dto.getPageSize();
    int firstResultIndex = (pageNumber - 1) * pageSize;
    typedQuery.setFirstResult(firstResultIndex);
    typedQuery.setMaxResults(dto.getPageSize());

    logger.debug(typedQuery.unwrap(org.hibernate.Query.class).getQueryString());
    List<Case> results = typedQuery.getResultList();

    return new ImmutablePair<>(count, results);

}

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

public List<Users> searchUserProfile(String searchTxt, String userOffers, String userSearchs, String orderBy,
        int start, int max, boolean asc) {
    try {/*from   www .ja v  a2 s . c  om*/

        String hql = "select c from Users c " + "where c.deleted = 'false' ";

        if (searchTxt.length() != 0 && userOffers.length() != 0 && userSearchs.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.login) LIKE :search " + "OR lower(c.firstname) LIKE :search "
                    + "OR lower(c.lastname) LIKE :search " + "OR lower(c.adresses.email) LIKE :search "
                    + "OR lower(c.adresses.town) LIKE :search " + ")" + "AND" + "("
                    + "lower(c.userOffers) LIKE :userOffers " + ")" + "AND" + "("
                    + "lower(c.userSearchs) LIKE :userSearchs " + ")" + ")";

        } else if (searchTxt.length() != 0 && userOffers.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.login) LIKE :search " + "OR lower(c.firstname) LIKE :search "
                    + "OR lower(c.lastname) LIKE :search " + "OR lower(c.adresses.email) LIKE :search "
                    + "OR lower(c.adresses.town) LIKE :search " + ")" + "AND" + "("
                    + "lower(c.userOffers) LIKE :userOffers " + ")" + ")";

        } else if (searchTxt.length() != 0 && userSearchs.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.login) LIKE :search " + "OR lower(c.firstname) LIKE :search "
                    + "OR lower(c.lastname) LIKE :search " + "OR lower(c.adresses.email) LIKE :search "
                    + "OR lower(c.adresses.town) LIKE :search " + ")" + "AND" + "("
                    + "lower(c.userSearchs) LIKE :userSearchs " + ")" + ")";

        } else if (userOffers.length() != 0 && userSearchs.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.userOffers) LIKE :userOffers " + ")" + "AND" + "("
                    + "lower(c.userSearchs) LIKE :userSearchs " + ")" + ")";

        } else if (searchTxt.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.login) LIKE :search " + "OR lower(c.firstname) LIKE :search "
                    + "OR lower(c.lastname) LIKE :search " + "OR lower(c.adresses.email) LIKE :search "
                    + "OR lower(c.adresses.town) LIKE :search " + ")" + ")";

        } else if (userOffers.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.userOffers) LIKE :userOffers " + ")" + ")";

        } else if (userSearchs.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.userSearchs) LIKE :userSearchs " + ")" + ")";

        }

        hql += " ORDER BY " + orderBy;

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

        if (searchTxt.length() != 0) {
            searchTxt = "%" + searchTxt + "%";
        }

        if (userOffers.length() != 0) {
            userOffers = "%" + userOffers + "%";
        }

        if (userSearchs.length() != 0) {
            userSearchs = "%" + userSearchs + "%";
        }

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

        // get all users
        TypedQuery<Users> query = em.createQuery(hql, Users.class);

        if (searchTxt.length() != 0 && userOffers.length() != 0 && userSearchs.length() != 0) {

            query.setParameter("search", StringUtils.lowerCase(searchTxt));
            query.setParameter("userOffers", StringUtils.lowerCase(userOffers));
            query.setParameter("userSearchs", StringUtils.lowerCase(userSearchs));

        } else if (searchTxt.length() != 0 && userOffers.length() != 0) {

            query.setParameter("search", StringUtils.lowerCase(searchTxt));
            query.setParameter("userOffers", StringUtils.lowerCase(userOffers));

        } else if (searchTxt.length() != 0 && userSearchs.length() != 0) {

            query.setParameter("search", StringUtils.lowerCase(searchTxt));
            query.setParameter("userSearchs", StringUtils.lowerCase(userSearchs));

        } else if (userOffers.length() != 0 && userSearchs.length() != 0) {

            query.setParameter("userOffers", StringUtils.lowerCase(userOffers));
            query.setParameter("userSearchs", StringUtils.lowerCase(userSearchs));

        } else if (searchTxt.length() != 0) {

            query.setParameter("search", StringUtils.lowerCase(searchTxt));

        } else if (userOffers.length() != 0) {

            query.setParameter("userOffers", StringUtils.lowerCase(userOffers));

        } else if (userSearchs.length() != 0) {

            query.setParameter("userSearchs", StringUtils.lowerCase(userSearchs));

        }

        query.setMaxResults(max);
        query.setFirstResult(start);

        List<Users> userList = query.getResultList();

        return userList;

    } catch (Exception ex2) {
        log.error("[getUsersList] ", ex2);
    }

    return null;
}

From source file:gov.osti.services.Metadata.java

/**
 * Acquire a listing of all records by OWNER.
 *
 * @param rows the number of rows desired (if present)
 * @param start the starting row number (from 0)
 * @return the Metadata information in the desired format
 * @throws JsonProcessingException/*from   w w  w. j  a  v a  2  s .  c o  m*/
 */
@GET
@Path("/projects")
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
public Response listProjects(@QueryParam("rows") int rows, @QueryParam("start") int start)
        throws JsonProcessingException {
    EntityManager em = DoeServletContextListener.createEntityManager();

    // get the security user in context
    Subject subject = SecurityUtils.getSubject();
    User user = (User) subject.getPrincipal();

    try {
        Set<String> roles = user.getRoles();
        String rolecode = (null == roles) ? "" : (roles.isEmpty()) ? "" : roles.iterator().next();

        TypedQuery<DOECodeMetadata> query;
        // admins see ALL PROJECTS
        if ("OSTI".equals(rolecode)) {
            query = em.createQuery("SELECT md FROM DOECodeMetadata md", DOECodeMetadata.class);
        } else if (StringUtils.isNotEmpty(rolecode)) {
            // if you have another ROLE, it is assumed to be a SITE ADMIN; see all those records
            query = em.createQuery("SELECT md FROM DOECodeMetadata md WHERE md.siteOwnershipCode = :site",
                    DOECodeMetadata.class).setParameter("site", rolecode);
        } else {
            // no roles, you see only YOUR OWN projects
            query = em.createQuery("SELECT md FROM DOECodeMetadata md WHERE md.owner = lower(:owner)",
                    DOECodeMetadata.class).setParameter("owner", user.getEmail());
        }

        // if rows specified, and greater than 100, cap it there
        rows = (rows > 100) ? 100 : rows;

        // if pagination elements are present, set them on the query
        if (0 != rows)
            query.setMaxResults(rows);
        if (0 != start)
            query.setFirstResult(start);

        // get a List of records
        RecordsList records = new RecordsList(query.getResultList());
        records.setStart(start);
        ObjectNode recordsObject = mapper.valueToTree(records);

        // lookup previous Snapshot status info for each item
        TypedQuery<MetadataSnapshot> querySnapshot = em
                .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class)
                .setParameter("status", DOECodeMetadata.Status.Approved);

        // lookup system Snapshot status info for each item
        TypedQuery<MetadataSnapshot> querySystemSnapshot = em
                .createNamedQuery("MetadataSnapshot.findByCodeIdAsSystemStatus", MetadataSnapshot.class)
                .setParameter("status", DOECodeMetadata.Status.Approved);

        JsonNode recordNode = recordsObject.get("records");
        if (recordNode.isArray()) {
            int rowCount = 0;
            for (JsonNode objNode : recordNode) {
                rowCount++;

                // skip non-approved records
                String currentStatus = objNode.get("workflow_status").asText();
                if (!currentStatus.equalsIgnoreCase("Approved"))
                    continue;

                // get code_id to find Snapshot
                long codeId = objNode.get("code_id").asLong();
                querySnapshot.setParameter("codeId", codeId);
                querySystemSnapshot.setParameter("codeId", codeId);

                String lastApprovalFor = "";
                List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList();
                for (MetadataSnapshot ms : results) {
                    lastApprovalFor = ms.getSnapshotKey().getSnapshotStatus().toString();
                }

                // add "approve as" status indicator to response record, if not blank
                if (!StringUtils.isBlank(lastApprovalFor))
                    ((ObjectNode) objNode).put("approved_as", lastApprovalFor);

                String systemStatus = "";
                List<MetadataSnapshot> resultsSystem = querySystemSnapshot.setMaxResults(1).getResultList();
                for (MetadataSnapshot ms : resultsSystem) {
                    systemStatus = ms.getSnapshotKey().getSnapshotStatus().toString();
                }

                // add "system status" indicator to response record, if not blank
                if (!StringUtils.isBlank(lastApprovalFor))
                    ((ObjectNode) objNode).put("system_status", systemStatus);
            }

            recordsObject.put("total", rowCount);
        }

        return Response.status(Response.Status.OK).entity(recordsObject.toString()).build();
    } finally {
        em.close();
    }
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Finds all {@link AlertHistoryEntity} that match the provided
 * {@link AlertHistoryRequest}. This method will make JPA do the heavy lifting
 * of providing a slice of the result set.
 *
 * @param request/*from  w  ww .  j a v  a2  s .  c  om*/
 * @return
 */
@RequiresSession
public List<AlertHistoryEntity> findAll(AlertHistoryRequest request) {
    EntityManager entityManager = m_entityManagerProvider.get();

    // convert the Ambari predicate into a JPA predicate
    HistoryPredicateVisitor visitor = new HistoryPredicateVisitor();
    PredicateHelper.visit(request.Predicate, visitor);

    CriteriaQuery<AlertHistoryEntity> query = visitor.getCriteriaQuery();
    javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate();

    if (null != jpaPredicate) {
        query.where(jpaPredicate);
    }

    // sorting
    JpaSortBuilder<AlertHistoryEntity> sortBuilder = new JpaSortBuilder<AlertHistoryEntity>();
    List<Order> sortOrders = sortBuilder.buildSortOrders(request.Sort, visitor);
    query.orderBy(sortOrders);

    // pagination
    TypedQuery<AlertHistoryEntity> typedQuery = entityManager.createQuery(query);
    if (null != request.Pagination) {
        typedQuery.setFirstResult(request.Pagination.getOffset());
        typedQuery.setMaxResults(request.Pagination.getPageSize());
    }

    return m_daoUtils.selectList(typedQuery);
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Finds all {@link AlertCurrentEntity} that match the provided
 * {@link AlertCurrentRequest}. This method will make JPA do the heavy lifting
 * of providing a slice of the result set.
 *
 * @param request//from ww w . j  ava 2  s  .com
 * @return
 */
@Transactional
public List<AlertCurrentEntity> findAll(AlertCurrentRequest request) {
    EntityManager entityManager = m_entityManagerProvider.get();

    // convert the Ambari predicate into a JPA predicate
    CurrentPredicateVisitor visitor = new CurrentPredicateVisitor();
    PredicateHelper.visit(request.Predicate, visitor);

    CriteriaQuery<AlertCurrentEntity> query = visitor.getCriteriaQuery();
    javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate();

    if (null != jpaPredicate) {
        query.where(jpaPredicate);
    }

    // sorting
    JpaSortBuilder<AlertCurrentEntity> sortBuilder = new JpaSortBuilder<AlertCurrentEntity>();
    List<Order> sortOrders = sortBuilder.buildSortOrders(request.Sort, visitor);
    query.orderBy(sortOrders);

    // pagination
    TypedQuery<AlertCurrentEntity> typedQuery = entityManager.createQuery(query);
    if (null != request.Pagination) {
        // prevent JPA errors when -1 is passed in by accident
        int offset = request.Pagination.getOffset();
        if (offset < 0) {
            offset = 0;
        }

        typedQuery.setFirstResult(offset);
        typedQuery.setMaxResults(request.Pagination.getPageSize());
    }

    List<AlertCurrentEntity> alerts = m_daoUtils.selectList(typedQuery);

    // if caching is enabled, replace results with cached values when present
    if (m_configuration.isAlertCacheEnabled()) {
        alerts = supplementWithCachedAlerts(alerts);
    }

    return alerts;
}

From source file:org.apache.openejb.util.proxy.QueryProxy.java

private <T> Query createFinderQuery(final EntityManager entityManager, final String methodName,
        final Class<T> entityType, final Object[] args) {
    final List<String> conditions = parseMethodName(methodName);

    final EntityType<T> et = entityManager.getMetamodel().entity(entityType);
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    CriteriaQuery<Object> query = cb.createQuery();
    final Root<T> from = query.from(entityType);
    query = query.select(from);/* ww  w.  j av a 2s . c om*/

    int i = 0;
    Predicate where = null;
    for (final String condition : conditions) {
        final SingularAttribute<? super T, ?> attribute = et.getSingularAttribute(condition);
        final Path<?> path = from.get(attribute);
        final Class<?> javaType = attribute.getType().getJavaType();

        final Predicate currentClause;
        if (javaType.equals(String.class)) {
            currentClause = cb.like((Expression<String>) path, (String) args[i++]);
        } else if (Number.class.isAssignableFrom(javaType) || javaType.isPrimitive()) {
            currentClause = cb.equal(path, args[i++]);
        } else {
            LOGGER.warning("field " + condition + " not found, ignoring");
            continue;
        }

        if (where == null) {
            where = currentClause;
        } else {
            where = cb.and(where, currentClause);
        }
    }

    if (where != null) {
        query = query.where(where);
    }

    // pagination
    final TypedQuery<?> emQuery = entityManager.createQuery(query);
    if (args != null && args.length == conditions.size() + 2 && isInt(args[args.length - 2].getClass())
            && isInt(args[args.length - 1].getClass())) {
        final int first = (Integer) args[args.length - 2];
        final int max = (Integer) args[args.length - 1];

        emQuery.setFirstResult(first);
        emQuery.setMaxResults(max);
    }

    return emQuery;
}

From source file:org.apache.openmeetings.data.user.dao.PrivateMessagesDao.java

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

        String hql = "select c from PrivateMessage 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<PrivateMessage> query = em.createQuery(hql, PrivateMessage.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<PrivateMessage> ll = query.getResultList();

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

From source file:org.apache.openmeetings.data.user.dao.PrivateMessagesDao.java

public List<PrivateMessage> getTrashPrivateMessagesByUser(Long user_id, String search, String orderBy,
        int start, Boolean asc, int max) {
    try {/*from w  w w.  java 2 s. c  o m*/

        String hql = "select c from PrivateMessage c " + "where c.isTrash = true "
                + "AND c.owner.user_id = :user_id ";

        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<PrivateMessage> query = em.createQuery(hql, PrivateMessage.class);
        if (search.length() != 0) {
            query.setParameter("search", StringUtils.lowerCase("%" + search + "%"));
        }
        query.setParameter("user_id", user_id);
        query.setFirstResult(start);
        query.setMaxResults(max);
        List<PrivateMessage> ll = query.getResultList();

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

From source file:org.apache.openmeetings.data.user.dao.PrivateMessagesDao.java

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

        String hql = "select c from PrivateMessage c " + "where c.from.user_id = :toUserId "
                + "AND c.isTrash = false " + "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<PrivateMessage> query = em.createQuery(hql, PrivateMessage.class);
        query.setParameter("toUserId", toUserId);
        query.setParameter("privateMessageFolderId", privateMessageFolderId);
        if (search.length() != 0) {
            query.setParameter("search", StringUtils.lowerCase("%" + search + "%"));
        }
        query.setFirstResult(start);
        query.setMaxResults(max);
        List<PrivateMessage> ll = query.getResultList();

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