@Override
  public PageBean findAppPictures(String currentPage, String factoryid) {
    // TODO Auto-generated method stub

    int curpage = Integer.parseInt(currentPage);
    int firdata = (curpage - 1) * 10;
    String param = "";

    Query query =
        getSession()
            .createQuery(
                "from App_picture  p where    p.factory.id='" + factoryid + "' "); // 带条件的查询语句
    int count = query.list().size();
    query.setFirstResult(firdata);
    query.setMaxResults(10);
    List<App_picture> list = query.list();
    while (list.size() == 0 && curpage > 1) {
      curpage -= 1;
      firdata = (curpage - 1) * 10;
      query =
          getSession()
              .createQuery(
                  "from App_picture p where    p.factory.id='" + factoryid + "' "); // 带条件的查询语句
      count = query.list().size();
      query.setFirstResult(firdata);
      query.setMaxResults(10);
      list = query.list();
      if (list.size() > 0) break;
    }
    PageBean pagebean = new PageBean(curpage, 10, count, list);
    return pagebean;
  }
 /**
  * 使用HQL进行分页查询.
  *
  * @param hql 查询条件
  * @param pageNo 页号,从1开始.
  * @param pageSize 每页中的记录数
  * @param args HQL的参数
  * @return 当前页的分页对象
  */
 public Page pagedQuery(String hql, int pageNo, int pageSize, Object... args) {
   Assert.hasText(hql);
   // 创建查询
   Query query = getSession().createQuery(hql);
   // 根据华南提出的bug做出修正,做是否为null的判断
   if (args != null) {
     for (int i = 0; i < args.length; i++) {
       query.setParameter(i, args[i]);
     }
   }
   String countQueryString = " SELECT count (*) " + removeSelect(removeOrders(hql));
   List countlist = getHibernateTemplate().find(countQueryString, args);
   long totalCount = (Long) countlist.get(0);
   // 返回分页对象
   if (totalCount < 1) return new Page();
   int startIndex = Page.getStartOfPage(pageNo, pageSize);
   List list;
   if (!entityQueryCache.isCached(hql, pageNo, pageSize, args)) {
     logger.debug("Not Using Cache for query: " + hql);
     list = query.setFirstResult(startIndex).setMaxResults(pageSize).list();
   } else {
     logger.debug("Using Cache for query: " + hql);
     list = new ArrayList();
     for (Iterator it = query.setFirstResult(startIndex).setMaxResults(pageSize).iterate();
         it.hasNext(); ) {
       list.add(it.next());
     }
   }
   return new Page(startIndex, totalCount, pageSize, list);
 }
  public int findCountByParams(
      String sql, boolean isHql, int start, int limit, Map<String, Object> params) {
    log.info("finding count by sql : " + sql);
    Session session = getHibernateTemplate().getSessionFactory().openSession();

    Query query = null;
    if ("".equals(sql) || sql == null) {
      query = session.createQuery("from FamilyMember");
    } else {
      if (isHql) {
        query = session.createQuery(sql);
      } else {
        query = session.createSQLQuery(sql);
      }
    }
    if (start > -1) {
      query.setFirstResult(start);
    }
    if (limit > -1) {
      query.setMaxResults(limit);
    }
    if (params != null) {
      for (String key : params.keySet()) {
        query.setParameter(key, params.get(key));
      }
    }
    // return ((Integer) query.uniqueResult()).intValue();
    return query.list().size();
  }
示例#4
0
  @SuppressWarnings("unchecked")
  public Pagination<Product> getProductsAtPageIndex(int index) {
    Pagination<Product> pagination = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      session.beginTransaction();
      String hql = "select count(p) from Product p";
      Long count = (Long) session.createQuery(hql).uniqueResult();

      // 计算分页信息
      pagination = new Pagination<Product>(count.intValue(), index, 5);
      hql = "from Product";
      Query query = session.createQuery(hql);
      query.setFirstResult(pagination.getFirstResultOffset());
      log.info("offset: " + pagination.getFirstResultOffset());
      query.setMaxResults(5);
      // query.setResultTransformer(Transformers.aliasToBean(Product.class));

      pagination.setObjectList((List<Product>) query.list());
    } finally {
      session.getTransaction().commit();
    }

    return pagination;
  }
示例#5
0
  /**
   * for a given locale, we can filter it by content state or search in source and target.
   *
   * @param documentId document id (NOT the String type docId)
   * @param hLocale locale
   * @param constraints filter constraints
   * @param firstResult start index
   * @param maxResult max result
   * @return a list of HTextFlow that matches the constraint.
   * @see
   *     org.zanata.service.impl.TextFlowSearchServiceImpl#findTextFlows(org.zanata.webtrans.shared.model.WorkspaceId,
   *     org.zanata.search.FilterConstraints)
   */
  public List<HTextFlow> getTextFlowByDocumentIdWithConstraints(
      DocumentId documentId,
      HLocale hLocale,
      FilterConstraints constraints,
      int firstResult,
      int maxResult) {
    FilterConstraintToQuery constraintToQuery =
        FilterConstraintToQuery.filterInSingleDocument(constraints, documentId);
    String queryString = constraintToQuery.toEntityQuery();
    log.debug("\n query {}\n", queryString);

    Query textFlowQuery = getSession().createQuery(queryString);
    constraintToQuery.setQueryParameters(textFlowQuery, hLocale);
    textFlowQuery.setFirstResult(firstResult).setMaxResults(maxResult);
    textFlowQuery
        .setCacheable(true)
        .setComment("TextFlowDAO.getTextFlowByDocumentIdWithConstraint");

    @SuppressWarnings("unchecked")
    List<HTextFlow> result = textFlowQuery.list();
    log.debug(
        "{} textFlow for locale {} filter by {}",
        result.size(),
        hLocale.getLocaleId(),
        constraints);
    return result;
  }
  @Override
  public List getShipmentHeader(String orderId, String mailId, int index, int size) {
    Session session = getSession();
    StringBuilder sb = new StringBuilder();
    sb.append("select a.senddt,a.shipment_id,a.mail_id,f.dsc,a.prod_price,");
    sb.append("e.address,c.name,a.order_id,a.mail_price from acoapp_oms.shipment_header a");
    sb.append(" inner join iagent.orderhist b on a.order_id = b.orderid");
    sb.append(" inner join iagent.contact c on b.contactid = c.contactid");
    sb.append(" inner join iagent.address e on b.addressid = e.addressid");
    sb.append(" left join iagent.names f on b.ordertype = f.id and f.tid = 'ORDERTYPE'");
    sb.append(
        " where CAST(a.logistics_status_id as NUMBER) >= 2 and CAST(a.logistics_status_id as NUMBER) not in (5,6)");
    sb.append(" and NVL(a.RECONCIL_FLAG,0)=0 and a.account_type = 1");
    if (!"".equals(orderId)) {
      sb.append(" and a.order_id = :orderId");
    }
    if (!"".equals(mailId)) {
      sb.append(" and a.mail_id = :mailId");
    }
    Query q = session.createSQLQuery(sb.toString());
    if (!"".equals(orderId) && orderId != null) {
      q.setString("orderId", orderId);
    }
    if (!"".equals(mailId) && mailId != null) {
      q.setString("mailId", mailId);
    }
    q.setFirstResult(index);
    q.setMaxResults(size);

    return q.list();
  }
示例#7
0
 /**
  * @param offset
  * @param limit
  * @return
  * @throws org.springframework.dao.DataAccessException
  */
 public List<I> find(Integer offset, Integer limit) {
   Session session = sessionFactory.getCurrentSession();
   Query query = session.createQuery("select a " + " from " + entityClass.getName() + " a");
   query.setFirstResult(offset);
   query.setMaxResults(limit);
   return (List<I>) query.list();
 }
示例#8
0
  @Override
  public List<Workshop> Paging(
      final int CurrentPage, final String WhereCond, final String SortBy, final boolean islast)
      throws Exception {
    // / TODO Auto-generated method stub
    final StringBuilder hql = new StringBuilder();
    List<Workshop> list = null;

    try {
      hql.append(this.strStatement);
      if (!WhereCond.equals("")) {
        hql.append(" where ");
        hql.append(WhereCond);
      }
      final Query selectQuery = this.session.createQuery(hql.toString());
      final long totalrecord = this.TotalRecord(this.strStatement, WhereCond);
      selectQuery.setFirstResult((int) ((totalrecord - 1) * this.pagesize));
      selectQuery.setMaxResults(this.pagesize);
      list = selectQuery.list();

    } catch (final Exception exp) {

      final ExceptionEntities lEntExp = new ExceptionEntities();
      lEntExp.setJavaClass(Thread.currentThread().getStackTrace()[1].getClassName());
      lEntExp.setMethodName(Thread.currentThread().getStackTrace()[1].getMethodName());
      ExceptionHelper.WriteException(lEntExp, exp);
    }
    return list;
  }
  @SuppressWarnings("unchecked")
  public <T> Pagination<T> find(Queryer queryer, int pageNo, int pageSize, Class<T> clazz) {
    int totalCount =
        ((Number) find(queryer.getCountHql(), queryer.getParameters().toArray()).get(0)).intValue();
    Pagination<T> pagination = new Pagination<T>(pageNo, pageSize, totalCount);
    int minPageNo = 1;
    int maxPageNo = pagination.getTotalPage();
    pageNo = pageNo < minPageNo ? minPageNo : pageNo;
    pageNo = pageNo > maxPageNo ? maxPageNo : pageNo;
    pagination.setPageNo(pageNo);

    if (totalCount == 0) {
      List<T> records = Collections.emptyList();
      pagination.setRecords(records);
      return pagination;
    }

    int first = (pageNo - 1) * pageSize;
    Query query = getSession().createQuery(queryer.getHql());

    int index = 0;

    for (Object parameter : queryer.getParameters()) {
      query.setParameter(index++, parameter);
    }

    query.setFirstResult(first);
    query.setMaxResults(pagination.getPageSize());
    List<T> list = query.list();
    pagination.setRecords(list);
    return pagination;
  }
示例#10
0
  public List<IpPoolManagement> findpublicIpsToPurchaseByVirtualDatacenter(
      final Integer vdcId,
      Integer startwith,
      final Integer limit,
      final String filter,
      final OrderByEnum orderByEnum,
      final Boolean descOrAsc) {
    Query finalQuery =
        getSession().createQuery(BY_VDC_TO_PURCHASE + " " + defineOrderBy(orderByEnum, descOrAsc));
    finalQuery.setParameter("vdc_id", vdcId);
    finalQuery.setParameter(
        "filterLike", filter == null || filter.isEmpty() ? "%" : "%" + filter + "%");

    // Check if the page requested is bigger than the last one
    Integer totalResults = finalQuery.list().size();

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

    if (startwith >= totalResults) {
      startwith = totalResults - limit;
    }
    finalQuery.setFirstResult(startwith);
    finalQuery.setMaxResults(limit);

    PagedList<IpPoolManagement> ipList = new PagedList<IpPoolManagement>(finalQuery.list());
    ipList.setTotalResults(totalResults);
    ipList.setPageSize(limit);
    ipList.setCurrentElement(startwith);

    return ipList;
  }
示例#11
0
  // Get list of products by category and product name
  // with times, every time 50 products
  public List<Product> getListProductByIdCategoryProductName(
      int categoryId, String productName, int times) {
    Query query = null;
    List<Product> listProduct = new ArrayList<Product>();
    String hql = "";
    int n = (times - 1) * 50;
    int m = times * 50;

    // Get category by categoryId
    Category category = categoryDao.get(categoryId, Category.class);

    try {
      hql =
          "FROM Product p WHERE p.productName LIKE :productName AND p.category = :category ORDER BY p.productName ";
      query = getSession().createQuery(hql);
      query.setString("productName", "%" + productName + "%");
      query.setParameter("category", category);
      if (times > 0) {
        query.setFirstResult(n);
        query.setMaxResults(m);
      }
      listProduct = query.list();
    } catch (Exception e) {
      e.printStackTrace();
      // log.error(e);
    }
    return listProduct;
  }
示例#12
0
 @SuppressWarnings("unchecked")
 public List<T> findList(
     String qlString,
     List<Object> parameter,
     Integer first,
     Integer count,
     List<Filter> filters,
     List<Order> orders) {
   StringBuilder stringBuilder = new StringBuilder(qlString);
   addFilter(stringBuilder, filters, parameter);
   addOrders(stringBuilder, orders, parameter);
   qlString = stringBuilder.toString();
   if (qlString.indexOf("order by") == -1) {
     if (OrderEntity.class.isAssignableFrom(this.entityClass)) {
       qlString += "order by order ASC";
     } else {
       qlString += "order by createDate DESC";
     }
   }
   System.out.println("productQuery = " + qlString);
   System.out.println(parameter.size());
   for (Object object : parameter) {
     System.out.println("object=" + object);
   }
   Query query = createQuery(qlString, parameter.toArray());
   if (first != null) {
     query.setFirstResult(first);
   }
   if (count != null) {
     query.setMaxResults(count);
   }
   return query.list();
 }
示例#13
0
  public Pager findAllUnconfirmedByProbationUnitId(
      String referenceId, Integer start, Integer size) {
    Pager pager = new Pager();

    start = (start == null) ? 0 : start;
    pager.setStart(start);

    size = (size == null) ? Pager.DEFAULT_PAGE_SIZE : size;
    pager.setSize(size);

    Query queryCount =
        getSession()
            .createQuery(
                "select count(ct) from ChildTransfer ct,LamaNivasa tl,ProbationUnit p where ct.toLamaNivasaId.id = tl.id and tl.probationUnit.id=p.id and p.id= :pid and ct.status=0");
    queryCount.setParameter("pid", referenceId);
    int listCount = ((Long) queryCount.uniqueResult()).intValue();
    pager.setTotal(listCount);

    Query query =
        getSession()
            .createQuery(
                "select ct from ChildTransfer ct,LamaNivasa tl,ProbationUnit p where ct.toLamaNivasaId.id = tl.id and tl.probationUnit.id=p.id and p.id= :pid and ct.status=0");

    query.setParameter("pid", referenceId);
    query.setFirstResult(start);
    query.setMaxResults(size);
    @SuppressWarnings("unchecked")
    List<ChildTransfer> list = query.list();

    pager.setList(list);

    return pager;
  }
示例#14
0
 @Override
 public List<Operator> getOperatorsPorced(int start, int size) {
   Query query = factory.getCurrentSession().createQuery("from Operator");
   query.setFirstResult(start);
   query.setMaxResults(size);
   return query.list();
 }
示例#15
0
  /**
   * 获取分页列表
   *
   * @param query String
   * @param args Object
   * @param pageNo int
   * @param pageSize int
   * @param count int
   * @return PageResult
   */
  public PageResult getList(String query, Object args[], int pageNo, int pageSize, int count) {
    logger.debug("query:" + query);
    PageResult pager = new PageResult();
    pager.setPageSize(pageSize);
    pager.setCurrentPageNo(pageNo);
    Session session = null;
    try {
      getHibernateTemplate().setAllowCreate(true);
      session = getSession();
      Query q = session.createQuery(query);

      if (args != null && args.length > 0) { // 设置参数
        for (int i = 0; i < args.length; i++) q.setParameter(i, args[i]);
      }
      pager.setTotalRecordCount(count); // 查询总记录数
      q.setFirstResult(pageSize * (pager.getCurrentPageNo() - 1));
      q.setMaxResults(pageSize);
      pager.setResults(q.list());

      q = null;
    } catch (HibernateException e) {
      logger.error(e);
    } finally {
      if (session != null) {
        releaseSession(session);
      }
    }
    return pager;
  }
示例#16
0
  /* (non-Javadoc)
   * @see com.adibrata.smartdealer.service.othertransactions.OtherReceive#Paging(int, java.lang.String, java.lang.String)
   */
  @SuppressWarnings("unchecked")
  @Override
  public List<OtherRcvHdr> Paging(int CurrentPage, String WhereCond, String SortBy)
      throws Exception {
    // TODO Auto-generated method stub
    StringBuilder hql = new StringBuilder();
    List<OtherRcvHdr> list = null;

    try {
      hql.append(strStatement);
      if (WhereCond != "") {
        hql.append(" where ");
        hql.append(WhereCond);
      }
      Query selectQuery = session.createQuery(hql.toString());
      long totalrecord = TotalRecord(WhereCond);
      selectQuery.setFirstResult((int) ((totalrecord - 1) * pagesize));
      selectQuery.setMaxResults(pagesize);
      list = selectQuery.list();

    } catch (Exception exp) {

      ExceptionEntities lEntExp = new ExceptionEntities();
      lEntExp.setJavaClass(Thread.currentThread().getStackTrace()[1].getClassName());
      lEntExp.setMethodName(Thread.currentThread().getStackTrace()[1].getMethodName());
      ExceptionHelper.WriteException(lEntExp, exp);
    }
    return list;
  }
 @SuppressWarnings("unchecked")
 public List<MessageBundleProperty> getModifiedProperties(
     int sortOrder, int sortField, int startingIndex, int pageSize) {
   String orderBy = "asc";
   if (sortOrder == SORT_ORDER_DESCENDING) {
     orderBy = "desc";
   }
   String sortFieldName = "id";
   if (sortField == SORT_FIELD_MODULE) {
     sortFieldName = "moduleName";
   }
   if (sortField == SORT_FIELD_PROPERTY) {
     sortFieldName = "propertyName";
   }
   if (sortField == SORT_FIELD_LOCALE) {
     sortFieldName = "locale";
   }
   if (sortField == SORT_FIELD_BASENAME) {
     sortFieldName = "baseName";
   }
   org.hibernate.Query query = null;
   String queryString =
       "from MessageBundleProperty where value != null order by " + sortFieldName + " " + orderBy;
   try {
     query = getSession().createQuery(queryString);
     query.setFirstResult(startingIndex);
     query.setMaxResults(pageSize);
     return query.list();
   } catch (HibernateException e) {
     throw new RuntimeException(e.getMessage(), e);
   }
 }
示例#18
0
 @SuppressWarnings("unchecked")
 @Override
 public <T> List<T> findList(String hql, Map<String, Object> paramMap, int start, int max) {
   Query query = getSession().createQuery(hql);
   setQuery(query, paramMap);
   return query.setFirstResult(start).setMaxResults(max).list();
 }
示例#19
0
 @SuppressWarnings("unchecked")
 public Page<T> findPage(String qlString, List<Object> parameter, Pageable pageable) {
   if (pageable == null) pageable = new Pageable();
   StringBuilder stringBuilder = new StringBuilder(qlString);
   addFilter(stringBuilder, pageable, parameter);
   addOrders(stringBuilder, pageable, parameter);
   qlString = stringBuilder.toString();
   if (qlString.indexOf("order by") == -1) {
     if (OrderEntity.class.isAssignableFrom(this.entityClass)) {
       qlString += "order by order ASC";
     } else {
       qlString += "order by createDate DESC";
     }
   }
   long count = count(stringBuilder, null, parameter);
   int i = (int) Math.ceil((double) count / pageable.getPageSize());
   if (i < pageable.getPageNumber()) {
     pageable.setPageNumber(i);
   }
   System.out.println("query=" + qlString);
   for (Object object : parameter) {
     System.out.println("object=" + object);
   }
   Query query = createQuery(qlString, parameter.toArray());
   query.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize());
   query.setMaxResults(pageable.getPageSize());
   List<Object> list = query.list();
   if (list.size() > 0) {
     return new Page<T>(query.list(), count, pageable);
   }
   List<T> listTemp = new ArrayList<T>();
   return new Page<T>(listTemp, count, pageable);
 }
示例#20
0
  public List<IpPoolManagement> findIpsByVdc(
      final Integer vdcId,
      Integer firstElem,
      final Integer numElem,
      final String has,
      final IpPoolManagement.OrderByEnum orderby,
      final Boolean asc) {
    // Get the query that counts the total results.
    Query finalQuery = getSession().createQuery(BY_VDC + " " + defineOrderBy(orderby, asc));
    finalQuery.setParameter("vdc_id", vdcId);
    finalQuery.setParameter("filterLike", has.isEmpty() ? "%" : "%" + has + "%");

    // Check if the page requested is bigger than the last one
    Integer totalResults = finalQuery.list().size();

    if (firstElem == null) {
      firstElem = 0;
    }

    if (firstElem >= totalResults) {
      firstElem = totalResults - numElem;
    }
    finalQuery.setFirstResult(firstElem);
    finalQuery.setMaxResults(numElem);

    PagedList<IpPoolManagement> ipList = new PagedList<IpPoolManagement>(finalQuery.list());
    ipList.setTotalResults(totalResults);
    ipList.setPageSize(numElem);
    ipList.setCurrentElement(firstElem);

    return ipList;
  }
 @Override
 public List<TrustDistrict> getListTrustDistrict(int pages, Boolean checkbox, String search)
     throws Exception {
   logger.info(
       "Execute function getListTrustDistrict with page ="
           + pages
           + " checkbox= "
           + checkbox
           + " search= "
           + search);
   session = HibernateUtil.getSessionFactory().openSession();
   try {
     String sql = "FROM TrustDistrict WHERE 1=1 ";
     if (!checkbox || checkbox == null) {
       sql += " AND ROW_ISACTIVE = true ";
     }
     if (!"".equals(search) || search == null) {
       sql += SearchLib.addSql(search, " row_name ");
     }
     Query query = session.createQuery(sql);
     query.setFirstResult((pages - 1) * UtilityFuntion.NUMBER_PAGE);
     query.setMaxResults(UtilityFuntion.NUMBER_PAGE);
     arrTrustDistrict = query.list();
   } catch (HibernateException he) {
     logger.error("Error HibernateException in getListTrustDistrict" + he);
     throw new Exception();
   } catch (Exception e) {
     logger.error("Error Exception in getListTrustDistrict" + e);
     throw new Exception();
   } finally {
     session.close();
   }
   return arrTrustDistrict;
 }
示例#22
0
 public List<VoltageLevel> findVoltageLevelListByPage(int pageNo, int pageSize) {
   Session session = this.getSession();
   Query query = session.createQuery("FROM VoltageLevel");
   query.setFirstResult((pageNo - 1) * pageSize);
   query.setMaxResults(pageSize);
   return query.list();
 }
示例#23
0
  /**
   * Return all the IPs from a VLAN filtered by a string and saying how many elements do you want
   * and the first element to retrieve
   *
   * @param network {@link Network} network entity that stores all the VLANs
   * @param vlanId identifier of the VLAN to search into.
   * @param has to filter the search
   * @param firstElem firstelement to retrieve.
   * @param numeElem to retrieve.
   * @return all the {@link IpPoolManagement} ips.
   */
  public List<IpPoolManagement> findIpsByNetwork(
      final Network network,
      final Integer vlanId,
      final String has,
      Integer firstElem,
      final Integer numElem) {
    Query finalQuery = getSession().createQuery(BY_NETWORK);
    finalQuery.setParameter("net_id", network.getId());
    finalQuery.setParameter("vlan_id", vlanId);
    finalQuery.setParameter("filterLike", has == null || has.isEmpty() ? "%" : "%" + has + "%");

    // Check if the page requested is bigger than the last one
    Integer totalResults = finalQuery.list().size();

    if (numElem != null) {
      finalQuery.setMaxResults(numElem);
    }

    if (firstElem >= totalResults) {
      firstElem = totalResults - 1;
      finalQuery.setMaxResults(1);
    }
    finalQuery.setFirstResult(firstElem);

    PagedList<IpPoolManagement> ipList = new PagedList<IpPoolManagement>(finalQuery.list());
    ipList.setTotalResults(totalResults);
    ipList.setPageSize(numElem);
    ipList.setCurrentElement(firstElem);

    return ipList;
  }
示例#24
0
 /**
  * QL 分页查询
  *
  * @param page
  * @param qlString
  * @param parameter
  * @return
  */
 @SuppressWarnings("unchecked")
 public <E> Page<E> find(Page<E> page, String qlString, Parameter parameter) {
   // get count
   if (!page.isDisabled() && !page.isNotCount()) {
     String countQlString = "select count(*) " + removeSelect(removeOrders(qlString));
     //	        page.setCount(Long.valueOf(createQuery(countQlString,
     // parameter).uniqueResult().toString()));
     Query query = createQuery(countQlString, parameter);
     List<Object> list = query.list();
     if (list.size() > 0) {
       page.setCount(Long.valueOf(list.get(0).toString()));
     } else {
       page.setCount(list.size());
     }
     if (page.getCount() < 1) {
       return page;
     }
   }
   // order by
   String ql = qlString;
   if (StringUtils.isNotBlank(page.getOrderBy())) {
     ql += " order by " + page.getOrderBy();
   }
   Query query = createQuery(ql, parameter);
   // set page
   if (!page.isDisabled()) {
     query.setFirstResult(page.getFirstResult());
     query.setMaxResults(page.getMaxResults());
   }
   page.setList(query.list());
   return page;
 }
  @SuppressWarnings("unchecked")
  @Override
  public Page<T> findByPage(Page<T> page, String hql, Object... values) {
    Query queryObject = createQuery(hql, values);

    List<?> count = queryObject.list();

    // 设置总条数
    if (count != null && count.size() > 0) {
      for (int i = 0; i < count.size(); i++) {
        int total = count.size();
        page.setTotal(total);

        // 分页
        if (page.getStart() > -1 && page.getPagesize() > -1) {
          queryObject.setFirstResult(page.getStart()).setMaxResults(page.getPagesize());
        }

        List<T> result = (List<T>) queryObject.list();
        page.setResult(result);
      }
    } else {
      page.setTotal(0);
    }
    return page;
  }
  /**
   * The information needed for the kundes table.
   *
   * @param rowIndex Integer
   * @throws EJBExceptionLP
   * @return QueryResult
   */
  public QueryResult getPageAt(Integer rowIndex) throws EJBExceptionLP {

    QueryResult result = null;
    SessionFactory factory = FLRSessionFactory.getFactory();
    Session session = null;
    try {
      int colCount = this.getTableInfo().getColumnClasses().length;
      int pageSize = PAGE_SIZE;
      int startIndex = Math.max(rowIndex.intValue() - (pageSize / 2), 0);
      int endIndex = startIndex + pageSize - 1;

      session = factory.openSession();
      String queryString =
          this.getFromClause() + this.buildWhereClause() + this.buildOrderByClause();

      Query query = session.createQuery(queryString);
      session = setFilter(session);

      query.setFirstResult(startIndex);
      query.setMaxResults(pageSize);
      List<?> resultList = query.list();
      Iterator<?> resultListIterator = resultList.iterator();

      Object[][] rows = new Object[resultList.size()][colCount];
      int row = 0;
      int col = 0;

      while (resultListIterator.hasNext()) {

        FLRLohnartstundenfaktor lohnartstundenfaktor =
            (FLRLohnartstundenfaktor) resultListIterator.next();

        rows[row][col++] = lohnartstundenfaktor.getI_id();
        rows[row][col++] = lohnartstundenfaktor.getFlrlohnart().getI_lohnart();
        rows[row][col++] = lohnartstundenfaktor.getFlrlohnart().getC_bez();
        rows[row][col++] = lohnartstundenfaktor.getFlrlohnart().getPersonalart_c_nr();
        rows[row][col++] = lohnartstundenfaktor.getF_faktor();

        String s = lohnartstundenfaktor.getFlrlohnstundenart().getC_nr();
        if (lohnartstundenfaktor.getFlrlohnstundenart().getC_bez() != null) {
          s = lohnartstundenfaktor.getFlrlohnstundenart().getC_bez();
        }
        rows[row][col++] = s;

        row++;
        col = 0;
      }
      result = new QueryResult(rows, this.getRowCount(), startIndex, endIndex, 0);
    } catch (Exception e) {
      throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e);
    } finally {
      try {
        session.close();
      } catch (HibernateException he) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER, he);
      }
    }
    return result;
  }
示例#27
0
  protected Query setPageParameterToQuery(Query q, Page<T> page) {
    AssertUtils.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

    q.setFirstResult(page.getOffset());
    q.setMaxResults(page.getPageSize());

    return q;
  }
示例#28
0
 public List getBuyMessageByType(int type, int start, int end) {
   String sql = "from Message m where m.type=?";
   Query query = this.getQuery(sql);
   query.setParameter(0, type);
   query.setFirstResult(start);
   query.setMaxResults(end - start);
   return query.list();
 }
示例#29
0
 public List getSendMessageByToId(int toId, int start, int end) {
   String sql = "from Message m where m.toid=?";
   Query query = this.getQuery(sql);
   query.setParameter(0, toId);
   query.setFirstResult(start);
   query.setMaxResults(end - start);
   return query.list();
 }
示例#30
0
  public List getMessageList(int start, int end) {
    String sql = "from Message";
    Query query = this.getQuery(sql);

    query.setFirstResult(start);
    query.setMaxResults(end - start);
    return query.list();
  }