Example #1
0
 public List<T> findAll(Integer number, Integer offset, String orderByPropertyName, boolean asc) {
   Session session = openSession(true);
   List<T> results = Lists.newArrayList();
   try {
     Criteria criteria = criteria().setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
     if (number != 1) {
       criteria.setFirstResult(number - 1);
     }
     if (offset != 0) {
       criteria.setMaxResults(offset);
     }
     if (asc) {
       criteria.addOrder(Order.asc(orderByPropertyName));
     } else {
       criteria.addOrder(Order.desc(orderByPropertyName));
     }
     results = list(criteria);
     for (T result : results) {
       result.init();
     }
     commitTransaction(session, true);
   } catch (Exception e) {
     rollbackTransaction(session, true);
   } finally {
     closeSession(session);
   }
   return results;
 }
  @Secured({"ROLE_DEVELOPER", "ROLE_TESTER"})
  @RequestMapping(value = "showBug/{bugId}.htm", method = RequestMethod.GET)
  public String showBug(@PathVariable Integer bugId, ModelMap map) {

    Bug bug = aService.findById(Bug.class, bugId);

    List<History> histories =
        aService.queryAllOfCondition(
            History.class,
            DetachedCriteria.forClass(History.class)
                .add(Restrictions.eq("objectType", "bug"))
                .add(Restrictions.eq("objectId", bug.getBugId()))
                .addOrder(Order.asc("operateTime")));
    List<Resource> resources =
        aService.queryAllOfCondition(
            Resource.class,
            DetachedCriteria.forClass(Resource.class)
                .add(Restrictions.eq("objectType", "bug"))
                .add(Restrictions.eq("objectId", bug.getBugId()))
                .addOrder(Order.asc("resourceId")));

    map.put("bug", bug);
    map.put("histories", histories);
    map.put("resources", resources);

    return "bug/showBug";
  }
 public EnhancedRule setRule(EnhancedRule rule, BlogCommentQuery query) {
   if (query != null) {
     if (query.name != null) {
       rule.add(Restrictions.like("name", query.name, MatchMode.ANYWHERE));
     }
     if (query.content != null) {
       rule.add(Restrictions.like("content", query.content, MatchMode.ANYWHERE));
     }
     if (query.email != null) {
       rule.add(Restrictions.like("email", query.email, MatchMode.ANYWHERE));
     }
     if (query.im != null) {
       rule.add(Restrictions.like("im", query.im, MatchMode.ANYWHERE));
     }
     if (query.ip != null) {
       rule.add(Restrictions.like("ip", query.ip, MatchMode.ANYWHERE));
     }
     if (query.website != null) {
       rule.add(Restrictions.like("website", query.website, MatchMode.ANYWHERE));
     }
     if (query.userId != null) {
       rule.add(Restrictions.eq("user.id", query.userId));
     }
     if (query.blogId != null) {
       rule.add(Restrictions.eq("blog.id", query.blogId));
     }
     if (query.getOrder() != null) {
       rule.addOrder(query.getDesc() ? Order.desc(query.getOrder()) : Order.asc(query.getOrder()));
     }
   }
   return rule;
 }
  private void buildOrderClause(
      StringBuilder queryStringBuilder,
      QueryModel queryModel,
      Criteria criteria,
      CriteriaQueryTranslator criteriaQueryTranslator) {
    boolean firstOrderItem = true;

    if (queryModel.getSorts() != null) {
      for (Sort sort : queryModel.getSorts()) {
        if (firstOrderItem) {
          queryStringBuilder.append(" order by ");
        } else {
          queryStringBuilder.append(',');
        }

        Order order =
            sort.getSortDirection() == SortDirection.Ascending
                ? Order.asc(sort.getField())
                : Order.desc(sort.getField());

        queryStringBuilder.append(order.toSqlString(criteria, criteriaQueryTranslator));

        firstOrderItem = false;
      }
    }
  }
  public List getAutoMobileList(
      int startLimit, int endLimit, AutomobileExpense autoMobile, String search_1st_order_by) {
    Session session = sessionFactory.openSession();
    List list = new ArrayList();

    try {
      Criteria criteria = createAutoMobileCriteria(session, autoMobile, "");
      if (StringUtils.isNotBlank(search_1st_order_by)) {
        criteria.addOrder(Order.desc(search_1st_order_by));
      }

      if (StringUtils.isBlank(search_1st_order_by)) {
        criteria.addOrder(Order.desc("automobileExpenseId"));
      }
      criteria.setFirstResult(startLimit);
      criteria.setMaxResults(endLimit);
      list = criteria.list();

    } catch (HibernateException e) {
      e.printStackTrace();
    } finally {
      session.close();
    }
    return list;
  }
Example #6
0
  private Criteria createCriteriaExactly(
      final Enterprise enterprise,
      final String filter,
      final String orderBy,
      final boolean desc,
      final boolean discardNullEnterprises) {
    Criteria criteria = createCriteria();

    if (enterprise != null) {
      if (discardNullEnterprises) {
        criteria.add(sameEnterprise(enterprise));
      } else {
        criteria.add(sameEnterpriseOrNull(enterprise));
      }

    } else {
      criteria.add(genericRole());
    }

    if (!StringUtils.isEmpty(filter)) {
      criteria.add(filterExactlyBy(filter));
    }

    if (!StringUtils.isEmpty(orderBy)) {
      Order order = Order.asc(orderBy);
      if (desc) {
        order = Order.desc(orderBy);
      }
      criteria.addOrder(order);
      criteria.addOrder(Order.asc(Role.NAME_PROPERTY));
    }

    return criteria;
  }
  @Override
  public DetachedCriteria buildCriteria() {

    DetachedCriteria crit = DetachedCriteria.forClass(AccountCreditNote.class);

    if (isNotEmpty(filterModel.getSerial())) {
      crit.add(Restrictions.ilike("this.serial", filterModel.getSerial(), MatchMode.START));
    }

    if (isNotEmpty(filterModel.getReference())) {
      crit.add(Restrictions.ilike("this.reference", filterModel.getReference(), MatchMode.START));
    }

    if (isNotEmpty(filterModel.getCode())) {
      crit.add(Restrictions.ilike("this.code", filterModel.getCode(), MatchMode.START));
    }

    if (filterModel.getBeginDate() != null) {
      crit.add(Restrictions.ge("this.date", filterModel.getBeginDate()));
    }

    if (filterModel.getEndDate() != null) {
      crit.add(Restrictions.le("this.date", filterModel.getEndDate()));
    }

    if (filterModel.getAccount() != null) {
      crit.add(Restrictions.le("this.account", filterModel.getAccount()));
    }

    crit.addOrder(Order.desc("serial"));
    crit.addOrder(Order.desc("date"));

    return crit;
  }
 @Override
 public <T extends GettableById> List<T> get(
     Class<T> bookEntityClass,
     int from,
     int to,
     Map<String, List<Criterion>> restrictions,
     OrderByFilter filter) {
   validateTransaction();
   Criteria criteria = getSession().createCriteria(bookEntityClass);
   criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
   criteria.setFirstResult(from);
   if (to != 0) criteria.setMaxResults(to);
   for (String key : restrictions.keySet()) {
     if (key.equals(RestrictionsFields.MAIN_RESTRICTIONS)) {
       for (Criterion restriction : restrictions.get(RestrictionsFields.MAIN_RESTRICTIONS))
         criteria.add(restriction);
     } else if (restrictions.get(key).size() > 0) {
       Criteria c = criteria.createCriteria(key);
       for (Criterion restriction : restrictions.get(key)) c.add(restriction);
     }
   }
   if (filter != null) {
     if (filter.getDirection().equals(OrderByFilter.ASC))
       criteria.addOrder(Order.asc(filter.field));
     else criteria.addOrder(Order.desc(filter.field));
   }
   return criteria.list();
 }
Example #9
0
 /**
  * 使用检索标准对象分页查询
  *
  * @param detachedCriteria
  * @param page
  * @return
  */
 @SuppressWarnings("unchecked")
 public Page<T> find(Page<T> page, DetachedCriteria detachedCriteria) {
   // get count
   if (!page.isDisabled() && !page.isNotCount()) {
     page.setCount(count(detachedCriteria));
     if (page.getCount() < 1) {
       return page;
     }
   }
   Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
   criteria.setResultTransformer(Criteria.ROOT_ENTITY);
   // set page
   if (!page.isDisabled()) {
     criteria.setFirstResult(page.getFirstResult());
     criteria.setMaxResults(page.getMaxResults());
   }
   // order by
   if (StringUtils.isNotBlank(page.getOrderBy())) {
     for (String order : StringUtils.split(page.getOrderBy(), ",")) {
       String[] o = StringUtils.split(order, " ");
       if (o.length >= 1) {
         criteria.addOrder(Order.asc(o[0]));
       } else if (o.length >= 2) {
         if ("DESC".equals(o[1].toUpperCase())) {
           criteria.addOrder(Order.desc(o[0]));
         } else {
           criteria.addOrder(Order.asc(o[0]));
         }
       }
     }
   }
   page.setList(criteria.list());
   return page;
 }
 /** Add order directly to criteria. */
 private static void addOrder(Criteria c, String sort, String order, boolean ignoreCase) {
   if (ORDER_DESC.equals(order)) {
     c.addOrder(ignoreCase ? Order.desc(sort).ignoreCase() : Order.desc(sort));
   } else {
     c.addOrder(ignoreCase ? Order.asc(sort).ignoreCase() : Order.asc(sort));
   }
 }
Example #11
0
  /*
   * (non-Javadoc)
   *
   * @see com.pfchoice.core.dao.ICDMeasureDao#getPage(int, int,
   * java.lang.String, java.lang.String, java.lang.String)
   */
  @Override
  public Pagination getPage(
      final int pageNo,
      final int pageSize,
      final String sSearch,
      final String sort,
      final String sortdir) {
    Criteria crit = createCriteria();

    if (sSearch != null && !"".equals(sSearch)) {
      Disjunction or = Restrictions.disjunction();

      or.add(Restrictions.ilike("code", "%" + sSearch + "%"))
          .add(Restrictions.ilike("description", "%" + sSearch + "%"))
          .add(Restrictions.ilike("hcc", "%" + sSearch + "%"))
          .add(Restrictions.ilike("rxhcc", "%" + sSearch + "%"));
      crit.add(or);
    }

    if (sort != null && !"".equals(sort)) {
      if (sortdir != null && !"".equals(sortdir) && "desc".equals(sortdir)) {
        crit.addOrder(Order.desc(sort));
      } else {
        crit.addOrder(Order.asc(sort));
      }
    }

    crit.add(Restrictions.eq("activeInd", 'Y'));
    return findByCriteria(crit, pageNo, pageSize);
  }
 public void build(Criteria criteria) {
   SortParam sort = sortState.getSort();
   String property;
   if (sort != null && sort.getProperty() != null) {
     property = sort.getProperty();
     asc = sort.isAscending();
   } else {
     property = defaultProperty;
   }
   if (property != null) {
     if (property.contains(".")) {
       // for 'dot' properties we need to add aliases
       // e.g. for the property 'orderbook.order.item.name' we need to add an aliases for 'order'
       // and 'order.item'
       String path[] = property.split("\\.");
       for (int ii = 0; ii < path.length - 1; ii++) {
         StringBuffer sb = new StringBuffer();
         for (int jj = 0; jj <= ii; jj++) {
           if (sb.length() > 0) sb.append(".");
           sb.append(path[jj]);
         }
         criteria.createAlias(sb.toString(), path[ii], CriteriaSpecification.LEFT_JOIN);
       }
       // when we have a 'dot' property we want to sort by the sub tables field
       // e.g. for the property 'orderbook.order.item.name' we need to sort by 'item.name'
       if (path.length > 1)
         property = String.format("%s.%s", path[path.length - 2], path[path.length - 1]);
       else property = path[path.length - 1];
     }
     Order order = asc ? Order.asc(property) : Order.desc(property);
     order = cased ? order : order.ignoreCase();
     criteria.addOrder(order);
   }
 }
  public Criteria createCriteria(
      String alias, int joinType, Page page, final Criterion... criterions) {
    Criteria criteria = getSession().createCriteria(entityClass);

    if (joinType == 0) {
      criteria.createAlias(alias, "_" + alias, CriteriaSpecification.INNER_JOIN);
    } else if (joinType == 1) {
      criteria.createAlias(alias, "_" + alias, CriteriaSpecification.LEFT_JOIN);
    } else if (joinType == 4) {
      criteria.createAlias(alias, "_" + alias, CriteriaSpecification.FULL_JOIN);
    }

    for (Criterion c : criterions) {
      criteria.add(c);
    }

    if (page.isOrderBySetted()) {
      String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
      String[] orderArray = StringUtils.split(page.getOrder(), ',');

      Assert.isTrue(orderByArray.length == orderArray.length, "多重排序参数中,排序字段与排序方向的个数不相等");

      for (int i = 0; i < orderByArray.length; i++) {
        if (Page.ASC.equals(orderArray[i])) {
          criteria.addOrder(Order.asc(orderByArray[i]));
        } else {
          criteria.addOrder(Order.desc(orderByArray[i]));
        }
      }
    }
    return criteria;
  }
  protected void addOrder(
      Criteria criteria, OrderByComparator orderByComparator, String... skipFields) {

    if (orderByComparator == null) {
      return;
    }

    String[] orderByFields = orderByComparator.getOrderByFields();

    Arrays.sort(skipFields);

    for (String orderByField : orderByFields) {
      Order order = null;

      String jbpmField = _fieldMap.get(orderByField);

      if (jbpmField == null) {
        jbpmField = orderByField;
      }

      if (Arrays.binarySearch(skipFields, jbpmField) < 0) {
        if (orderByComparator.isAscending()) {
          order = Order.asc(jbpmField);
        } else {
          order = Order.desc(jbpmField);
        }

        criteria.addOrder(order);
      }
    }
  }
  @SuppressWarnings("unchecked")
  @Override
  public List<PersonneStatut> rechercherStatutParCriteres(DimensionCriteresRechercheDto criteres) {

    final Criteria criteria = createCriteria(PersonneStatut.class);

    // Critère sur l'identifiant
    if (criteres.getId() != null) {
      criteria.add(Restrictions.eq("id", criteres.getId()));
    }
    // Critère sur le libelle
    if (criteres.getLibelle() != null && !criteres.getLibelle().equals("")) {
      criteria.add(Restrictions.ilike("libelle", criteres.getLibelle().toLowerCase() + "%"));
    }
    // Critère sur la visibilité
    if (criteres.getVisible() != null) {
      criteria.add(Restrictions.eq("visible", criteres.getVisible()));
    }
    // Maxresults
    if (criteres.getMaxResults() != null) {
      criteria.setFirstResult(0);
      criteria.setMaxResults(criteres.getMaxResults());
    }
    // Ordonner les éléments
    criteria.addOrder(Order.asc("ordre"));
    criteria.addOrder(Order.asc("libelle"));

    return criteria.list();
  }
  @Override
  public Iterable<T> findUsingQueryModel(QueryModel queryModel) {
    if (accessControlContextProvider == null
        || roleAllowsAccess(queryModel.getAccessControlContext().getRole())) {
      Criteria criteria = buildCriteria(queryModel);

      if (queryModel.getSorts() != null) {
        for (Sort sort : queryModel.getSorts()) {
          criteria.addOrder(
              sort.getSortDirection() == SortDirection.Ascending
                  ? Order.asc(sort.getField())
                  : Order.desc(sort.getField()));
        }
      }

      if (queryModel.getMaxResults() > 0) {
        criteria.setMaxResults(queryModel.getMaxResults());
      }

      if (queryModel.getFirstResult() > 0) {
        criteria.setFirstResult(queryModel.getFirstResult());
      }

      //noinspection unchecked
      return criteria.list();
    } else {
      //noinspection unchecked
      return createEntryBasedQuery(queryModel).list();
    }
  }
Example #17
0
  /**
   * prepare query based on criteria
   *
   * @param session hib session
   * @return the query
   */
  private Criteria attachCriteriaInfo(Session session) {
    Criteria query = null;

    if (StringUtils.isBlank(this.entityName)) {
      if (StringUtils.isBlank(this.alias)) {
        query = session.createCriteria(this.persistentClass);
      } else {
        query = session.createCriteria(this.persistentClass, alias);
      }
    } else {
      query = session.createCriteria(this.entityName);
    }

    // add criterions
    if (this.criterions != null) {
      query.add(this.criterions);
    }
    boolean secondLevelCaching =
        HibUtils.secondLevelCaching(
            ByCriteriaStatic.this.cacheable, ByCriteriaStatic.this.queryOptions);
    query.setCacheable(secondLevelCaching);

    if (secondLevelCaching) {
      String secondLevelCacheRegion =
          HibUtils.secondLevelCacheRegion(
              ByCriteriaStatic.this.cacheRegion, ByCriteriaStatic.this.queryOptions);
      if (!StringUtils.isBlank(secondLevelCacheRegion)) {
        query.setCacheRegion(secondLevelCacheRegion);
      }
    }

    QuerySort querySort = this.queryOptions == null ? null : this.queryOptions.getQuerySort();
    if (querySort != null) {
      List<QuerySortField> sorts = querySort.getQuerySortFields();

      for (QuerySortField theSort : GrouperUtil.nonNull(sorts)) {

        Order order =
            theSort.isAscending()
                ? Order.asc(theSort.getColumn())
                : Order.desc(theSort.getColumn());

        query.addOrder(order);
      }
    }
    QueryPaging queryPaging = this.queryOptions == null ? null : this.queryOptions.getQueryPaging();
    if (queryPaging != null) {

      // GRP-1024: sql server problems with paging page number when not initted
      if (queryPaging.getFirstIndexOnPage() < 0) {
        query.setFirstResult(0);
      } else {
        query.setFirstResult(queryPaging.getFirstIndexOnPage());
      }

      query.setMaxResults(queryPaging.getPageSize());
    }

    return query;
  }
Example #18
0
  @SuppressWarnings("unchecked")
  public List<Token> findTokens(
      Token search, int first, int pageSize, String sortField, SortOrder sortOrder)
      throws DAOException {
    List<Token> results = null;
    Session session = null;
    try {
      session = getSession();
      Criteria criteria = criteria(session, search);

      criteria.setFirstResult(first);
      criteria.setMaxResults(pageSize);

      if (sortField == null) {
        sortField = "tokenId";
      }

      Order ord =
          (sortOrder == null
                  || sortOrder.equals(SortOrder.UNSORTED)
                  || sortOrder.equals(SortOrder.ASCENDING))
              ? Order.asc(sortField)
              : Order.desc(sortField);
      criteria.addOrder(ord);

      results = criteria.list();
    } catch (Exception e) {
      throw new DAOException(e);
    } finally {
      if (session != null) {
        session.close();
      }
    }
    return results;
  }
Example #19
0
  public Map<String, Object> lista(Map<String, Object> params) {
    log.debug("Buscando lista de facturas con params {}", params);
    if (params == null) {
      params = new HashMap<>();
    }

    if (!params.containsKey("max")) {
      params.put("max", 10);
    } else {
      params.put("max", Math.min((Integer) params.get("max"), 100));
    }

    if (params.containsKey("pagina")) {
      Long pagina = (Long) params.get("pagina");
      Long offset = (pagina - 1) * (Integer) params.get("max");
      params.put("offset", offset.intValue());
    }

    if (!params.containsKey("offset")) {
      params.put("offset", 0);
    }
    Criteria criteria = currentSession().createCriteria(FacturaAlmacen.class);
    Criteria countCriteria = currentSession().createCriteria(FacturaAlmacen.class);

    if (params.containsKey("almacen")) {
      criteria.createCriteria("almacen").add(Restrictions.idEq(params.get("almacen")));
      countCriteria.createCriteria("almacen").add(Restrictions.idEq(params.get("almacen")));
    }

    if (params.containsKey("filtro")) {
      String filtro = (String) params.get("filtro");
      Disjunction propiedades = Restrictions.disjunction();
      propiedades.add(Restrictions.ilike("folio", filtro, MatchMode.ANYWHERE));
      criteria.add(propiedades);
      countCriteria.add(propiedades);
    }

    if (params.containsKey("order")) {
      String campo = (String) params.get("order");
      if (params.get("sort").equals("desc")) {
        criteria.addOrder(Order.desc(campo));
      } else {
        criteria.addOrder(Order.asc(campo));
      }
    } else {
      criteria.createCriteria("estatus").addOrder(Order.asc("prioridad"));
    }
    criteria.addOrder(Order.desc("fechaModificacion"));

    if (!params.containsKey("reporte")) {
      criteria.setFirstResult((Integer) params.get("offset"));
      criteria.setMaxResults((Integer) params.get("max"));
    }
    params.put("facturas", criteria.list());

    countCriteria.setProjection(Projections.rowCount());
    params.put("cantidad", (Long) countCriteria.list().get(0));

    return params;
  }
 /**
  * Adiciona ordenação a uma criteria.
  *
  * @param propriedade Propriedade utilizada na ordenação.
  * @param ascendente true caso ascendente, false caso descendente.
  * @param criteria Criteria na qual a ordenação será adicionada.
  */
 protected void adicionarOrdenacao(String propriedade, boolean ascendente, Criteria criteria) {
   if (ascendente) {
     criteria.addOrder(Order.asc(propriedade).ignoreCase());
   } else {
     criteria.addOrder(Order.desc(propriedade).ignoreCase());
   }
 }
Example #21
0
 @Override
 public List<Participation> getMarkersAvailableParticipations(Group group) {
   if (group.getTutors().size() > 0) {
     Integer[] ids = new Integer[group.getTutors().size()];
     int i = 0;
     for (Participation participation : group.getTutors()) {
       ids[i++] = participation.getId();
     }
     return getSession()
         .createCriteria(Participation.class)
         .add(Restrictions.eq("lecture", group.getLecture()))
         .add(
             Restrictions.or(
                 Restrictions.eq("role", ParticipationRole.TUTOR.toString()),
                 Restrictions.eq("role", ParticipationRole.ADVISOR.toString())))
         .add(Restrictions.not(Restrictions.in("id", ids)))
         .createCriteria("user")
         .addOrder(Order.asc("lastName"))
         .addOrder(Order.asc("firstName"))
         .list();
   } else {
     return getSession()
         .createCriteria(Participation.class)
         .add(Restrictions.eq("lecture", group.getLecture()))
         .add(
             Restrictions.or(
                 Restrictions.eq("role", ParticipationRole.TUTOR.toString()),
                 Restrictions.eq("role", ParticipationRole.ADVISOR.toString())))
         .createCriteria("user")
         .addOrder(Order.asc("lastName"))
         .addOrder(Order.asc("firstName"))
         .list();
   }
 }
Example #22
0
 public List getAllUsers() {
   Criteria objCriteria = null;
   Session objSession = null;
   List objList = null;
   try {
     logger.info("GETTING ALL USERS");
     objSession = HibernateUtil.getSession();
     objCriteria =
         objSession
             .createCriteria(UsersVO.class)
             .add(Restrictions.eq("valid", new Boolean(true)))
             .addOrder(Order.asc("firstName"));
     objCriteria.addOrder(Order.asc("userId"));
     objList = objCriteria.list();
     logger.info("GET ALL USERS ENDS");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET ALL USERS", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return objList;
 }
Example #23
0
  /**
   * bar info query
   *
   * @param global
   * @return
   * @throws JSONException
   */
  public String queryBarInfo(String global) throws JSONException {
    DetachedCriteria dc = DetachedCriteria.forClass(TNavigation.class);
    dc.add(Restrictions.eq("status", 1));
    dc.addOrder(Order.asc("ordinal")).addOrder(Order.desc("updatetime"));

    List<TNavigation> list = super.findByDetachedCriteria(dc);
    List<TBar> rootList = new ArrayList<TBar>();
    for (TNavigation navtion : list) {
      if ("0".equals(navtion.getObjid())) {
        TBar bar = new TBar();
        bar.setName(ActionUtils.getLanStr(navtion.getName(), navtion.getEname(), global));
        bar.setId(navtion.getOid());
        bar.setObjid(navtion.getObjid());

        rootList.add(bar);
      }
    }
    TNavigation record = new TNavigation();
    record.getBarList().add(rootList);
    record = this.convertBar(record, rootList, list, global);

    //		JSONArray itms = (JSONArray) JSONSerializer.toJSON(record.getBarList());
    //		return itms.toString();
    return JSONUtil.serialize(record.getBarList(), null, null, false, false, true);
  }
Example #24
0
 /** 创建Criteria对象,带排序字段与升降序字段. */
 public Criteria createCriteria(String orderBy, boolean isAsc, Criterion... criterions) {
   Assert.hasText(orderBy);
   Criteria criteria = createCriteria(criterions);
   if (isAsc) criteria.addOrder(Order.asc(orderBy));
   else criteria.addOrder(Order.desc(orderBy));
   return criteria;
 }
  public Pager list(String username, int pageSize, int pageNo) {
    Session session = null;
    Pager pager = null;
    try {
      session = HibernateSessionFactory.currentSession();

      Criteria criteria = session.createCriteria(Schedule.class);
      criteria.add(Restrictions.eq("username", username));

      int rowCount =
          ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
      criteria.setProjection(null);

      int startIndex = pageSize * (pageNo - 1);

      criteria.addOrder(Order.desc("year"));
      criteria.addOrder(Order.desc("month"));
      criteria.addOrder(Order.desc("day"));
      criteria.setFirstResult(startIndex);
      criteria.setMaxResults(pageSize);
      List<?> result = criteria.list();
      pager = new Pager(pageSize, pageNo, rowCount, result);
    } catch (HibernateException e) {
      pager = new Pager(pageSize, pageNo, 0, new ArrayList<Object>());
      throw e;
    } finally {
      HibernateSessionFactory.closeSession();
    }
    return pager;
  }
  @Override
  @Transactional(readOnly = true)
  public AnnotationView[] listAnnotationsNoReplies(
      final Long articleID,
      final Set<AnnotationType> annotationTypes,
      final AnnotationOrder order) {
    if (order == AnnotationOrder.MOST_RECENT_REPLY) {
      throw new IllegalArgumentException(
          "Cannot specify Most Recent Reply order type when replies are not being loaded up");
    }
    // Basic criteria
    DetachedCriteria criteria =
        DetachedCriteria.forClass(Annotation.class)
            .add(Restrictions.eq("articleID", articleID))
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    // restrict by type
    if (annotationTypes != null && !annotationTypes.isEmpty()) {
      criteria.add(Restrictions.in("type", annotationTypes));
    }
    switch (order) {
      case OLDEST_TO_NEWEST:
        criteria.addOrder(Order.asc("created"));
        break;
      case NEWEST_TO_OLDEST:
        criteria.addOrder(Order.desc("created"));
        break;
    }
    List annotationResults = hibernateTemplate.findByCriteria(criteria);
    // Don't want to call buildAnnotationView() here because that would involve finding the article
    // title and doi for each annotation,
    // when we only need to do it once. So load up the info we need to build annotation views here
    Object[] articleTitleAndDoi;
    try {
      articleTitleAndDoi =
          (Object[])
              hibernateTemplate
                  .findByCriteria(
                      DetachedCriteria.forClass(Article.class)
                          .add(Restrictions.eq("ID", articleID))
                          .setProjection(
                              Projections.projectionList()
                                  .add(Projections.property("doi"))
                                  .add(Projections.property("title"))),
                      0,
                      1)
                  .get(0);

    } catch (IndexOutOfBoundsException e) {
      throw new IllegalArgumentException("article " + articleID + " didn't exist");
    }
    String articleDoi = (String) articleTitleAndDoi[0];
    String articleTitle = (String) articleTitleAndDoi[1];

    List<AnnotationView> viewResults = new ArrayList<AnnotationView>(annotationResults.size());
    for (Object annotation : annotationResults) {
      viewResults.add(new AnnotationView((Annotation) annotation, articleDoi, articleTitle, null));
    }
    return viewResults.toArray(new AnnotationView[viewResults.size()]);
  }
  @Scheduled(fixedDelay = 60000)
  public void changeSessionStatus() {

    List<CurrentUsersDTO> allList = null;
    List<CurrentUsersDTO> activeList = null;

    String currentTime = getTime();
    String beforeTime = getBeforeTime();
    String beforeHeartBeatTime = getBeforeHeartBeatTime();

    Session session = getSession();
    session.getTransaction().begin();

    Criteria criteria =
        session
            .createCriteria(SessionDetails.class, "sessionDetails")
            .add(
                Restrictions.between(
                    "sessionDetails.heartBeatTime", beforeHeartBeatTime, currentTime))
            .add(Restrictions.between("sessionDetails.lastAccessTime", beforeTime, currentTime));
    criteria.addOrder(Order.asc("SID"));
    criteria.setProjection(
        Projections.projectionList()
            .add(Projections.property("SID").as("sid"))
            .add(Projections.property("lastAccessTime").as("lastAccessTime")));
    activeList =
        criteria.setResultTransformer(Transformers.aliasToBean(CurrentUsersDTO.class)).list();

    Criteria criteria1 = session.createCriteria(SessionDetails.class, "sessionDetails");
    criteria1.addOrder(Order.asc("SID"));
    criteria1.setProjection(
        Projections.projectionList()
            .add(Projections.property("SID").as("sid"))
            .add(Projections.property("lastAccessTime").as("lastAccessTime")));
    allList =
        criteria1.setResultTransformer(Transformers.aliasToBean(CurrentUsersDTO.class)).list();

    for (CurrentUsersDTO dto : allList) {
      try {
        SessionDetails sd = getById(dto.getSid());
        sd.setStatus("INACTIVE");
        saveSessionDetails(sd);
      } catch (Exception e) {
        System.out.println("E :" + e);
      }
    }

    for (CurrentUsersDTO dto : activeList) {
      try {
        SessionDetails sd = getById(dto.getSid());
        sd.setStatus("ACTIVE");
        saveSessionDetails(sd);
      } catch (Exception e) {
        System.out.println("E :" + e);
      }
    }
    session.getTransaction().commit();
    session.close();
  }
 public List<DailySummary> getDailySummarys(String[] para) {
   DetachedCriteria criteria = DetachedCriteria.forClass(DailySummary.class);
   criteria.add(Restrictions.eq("stockSymbol", para[0]));
   criteria.add(Restrictions.between("date", para[1], para[2]));
   if (para[3].equalsIgnoreCase("desc")) criteria.addOrder(Order.desc("date"));
   else criteria.addOrder(Order.asc("date"));
   return (List<DailySummary>) dao.getHibernateTemplate().findByCriteria(criteria);
 }
Example #29
0
 /**
  * 得到所有 数据
  *
  * @param orderBy 排序字段
  * @param isAsc 是否排序
  * @return
  */
 public List<T> getAll(String orderBy, boolean isAsc) {
   Criteria c = createCriteria(new Criterion[0]);
   if (isAsc) c.addOrder(Order.asc(orderBy));
   else {
     c.addOrder(Order.desc(orderBy));
   }
   return c.list();
 }
  /*
   * (non-Javadoc)
   *
   * @see com.changpeng.common.action.AbstractAction#go()
   */
  @Override
  protected String go() throws Exception {
    this.lawyer = this.getLoginUser();
    // TODO Auto-generated method stub
    BasicService basic = (BasicService) getBean("basicService");
    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Articles.class);
    detachedCriteria.add(Restrictions.eq("type", type));

    if (type == 1) { // 重要通知才搞这个。那个什么帮助就都显示了
      // Criterion province = Restrictions.eq("provinceid",
      // this.getLoginUser().getProvinceid());

      int directunion = this.getLoginUser().getDirectunion();
      SysGroup group = (SysGroup) basic.get(SysGroup.class, directunion);

      detachedCriteria.add(Restrictions.eq("status", 0));
      // 显示我的事务所的通知,显示我的律协的通知,显示我的省律协的通知,显示系统的通只
      // detachedCriteria.add(Restrictions.in("thegroup", new Integer[] {
      // this.getLoginUser().getProvinceunion(),
      // this.getLoginUser().getDirectunion(),
      // this.getLoginUser().getTheoffice(), 0 }));

      Criterion province =
          Restrictions.in(
              "thegroup",
              new Integer[] {
                this.getLoginUser().getProvinceunion(),
                this.getLoginUser().getDirectunion(),
                this.getLoginUser().getTheoffice(),
                0
              });

      Criterion c = Restrictions.eq("provinceid", 0);
      detachedCriteria.add(Restrictions.or(c, province));

      detachedCriteria.addOrder(Order.desc("createtime"));
    }

    // 按现实顺序来
    detachedCriteria.addOrder(Order.desc("listorder"));
    detachedCriteria.addOrder(Order.desc("createtime"));

    this.page = basic.findPageByCriteria(detachedCriteria, pageSize, pageNo);

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -1); // 得到前一天
    cal.add(Calendar.MONTH, -1); // 得到前一个月
    long date = cal.getTimeInMillis();
    System.out.println(date);
    // long lastdaya=df.format(new java.util.Date(date));
    // System.out.println(lastdaya);
    lastday = new Timestamp(date);
    System.out.println(lastday);

    // TODO Auto-generated method stub
    return SUCCESS;
  }