示例#1
0
  /**
   * Get a list of entities based on the provided criteria and entity type.
   *
   * @param criteria
   * @param type
   * @throws StorageException if a storage problem occurs while storing a bean
   */
  protected <T> SearchResultsBean<T> find(SearchCriteriaBean criteria, Class<T> type)
      throws StorageException {
    SearchResultsBean<T> results = new SearchResultsBean<>();
    EntityManager entityManager = getActiveEntityManager();
    try {
      // Set some default in the case that paging information was not included in the request.
      PagingBean paging = criteria.getPaging();
      if (paging == null) {
        paging = new PagingBean();
        paging.setPage(1);
        paging.setPageSize(20);
      }
      int page = paging.getPage();
      int pageSize = paging.getPageSize();
      int start = (page - 1) * pageSize;

      CriteriaBuilder builder = entityManager.getCriteriaBuilder();
      CriteriaQuery<T> criteriaQuery = builder.createQuery(type);
      Root<T> from = criteriaQuery.from(type);
      applySearchCriteriaToQuery(criteria, builder, criteriaQuery, from, false);
      TypedQuery<T> typedQuery = entityManager.createQuery(criteriaQuery);
      typedQuery.setFirstResult(start);
      typedQuery.setMaxResults(pageSize + 1);
      boolean hasMore = false;

      // Now query for the actual results
      List<T> resultList = typedQuery.getResultList();

      // Check if we got back more than we actually needed.
      if (resultList.size() > pageSize) {
        resultList.remove(resultList.size() - 1);
        hasMore = true;
      }

      // If there are more results than we needed, then we will need to do another
      // query to determine how many rows there are in total
      int totalSize = start + resultList.size();
      if (hasMore) {
        totalSize = executeCountQuery(criteria, entityManager, type);
      }
      results.setTotalSize(totalSize);
      results.setBeans(resultList);
      return results;
    } catch (Throwable t) {
      logger.error(t.getMessage(), t);
      throw new StorageException(t);
    }
  }