Exemple #1
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;
  }
  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;
  }
  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;
  }
 /**
  * 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());
   }
 }
Exemple #5
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;
 }
Exemple #6
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;
  }
 /** 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));
   }
 }
  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;
  }
  /*
   * (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);
  }
 @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();
 }
 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;
 }
  @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();
  }
Exemple #13
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;
 }
  @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();
  }
Exemple #15
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();
 }
 public List<User> findUsers(Object... params) {
   Criteria criteria = createDefaultCriteria(User.class);
   handleSpecificFetchMode(criteria, params);
   criteria.addOrder(Order.asc("lastname"));
   criteria.addOrder(Order.asc("firstname"));
   @SuppressWarnings("unchecked")
   List<User> users = criteria.list();
   return users;
 }
 @Override
 public void buildOrdered(Criteria criteria) {
   buildUnordered(criteria);
   SortParam<String> sort = ((SingleSortState<String>) getSortState()).getSort();
   if (sort != null) {
     if (sort.isAscending()) criteria.addOrder(Order.asc(sort.getProperty()).ignoreCase());
     else criteria.addOrder(Order.desc(sort.getProperty()).ignoreCase());
   }
 }
Exemple #18
0
  public HashMap getAllUsers(
      Filter filterUserId,
      int userTypeId,
      String parentTypeId,
      String sortBy,
      boolean ascending,
      int startIndex,
      int displayCount) {
    Criteria objCriteria = null;
    Session objSession = null;
    Integer totRecordCount = null;
    List objList = null;
    HashMap hmResult = new HashMap();
    try {
      logger.info("GETING ALL USERS");
      objSession = HibernateUtil.getSession();
      objCriteria = objSession.createCriteria(UsersVO.class);

      if (filterUserId != null) {
        objCriteria.add(
            Restrictions.like(
                filterUserId.getFieldName(),
                filterUserId.getFieldValue(),
                (MatchMode) HibernateUtil.htMatchCase.get(filterUserId.getSpecialFunction())));
      }

      if (userTypeId != 0) {
        objCriteria.add(Restrictions.eq("userTypes.userTypeId", new Integer(userTypeId)));
      }

      if (parentTypeId.length() > 0) {
        objCriteria.add(Restrictions.like("parentUser.userId", parentTypeId, MatchMode.EXACT));
      }

      totRecordCount = new Integer(objCriteria.list().size());
      if (ascending) {
        objCriteria.addOrder(Order.asc(sortBy));
      } else {
        objCriteria.addOrder(Order.desc(sortBy));
      }
      objCriteria.setFirstResult(startIndex);
      objCriteria.setMaxResults(displayCount);
      objList = objCriteria.list();
      hmResult.put("TotalRecordCount", totRecordCount);
      hmResult.put("Records", objList);
      logger.info("GOT ALL USERS");
    } catch (HibernateException e) {
      logger.error("HIBERNATE EXCEPTION DURING GET ALL USERS", e);
      e.printStackTrace();
    } finally {
      if (objSession != null) {
        objSession.close();
      }
    }
    return hmResult;
  }
 @Override
 @SuppressWarnings("unchecked")
 public List<CommentModel> findByAllWithCriteria() {
   Session session = sessionFactory.getCurrentSession();
   Criteria cr = session.createCriteria(CommentModel.class);
   cr.addOrder(Order.asc("commentId"));
   cr.addOrder(Order.desc("commentTitle"));
   List<CommentModel> result = cr.list();
   return result;
 }
 /** 获取全部对象, 支持按属性行序. */
 @SuppressWarnings("unchecked")
 public List<T> getAll(String orderByProperty, boolean isAsc) {
   Criteria c = createCriteria();
   if (isAsc) {
     c.addOrder(Order.asc(orderByProperty));
   } else {
     c.addOrder(Order.desc(orderByProperty));
   }
   return c.list();
 }
 public List<DictEstate> listDictEstateParent() {
   Criteria listCriteria = getSession().createCriteria(DictEstate.class);
   listCriteria.addOrder(Order.asc("value"));
   //        Criteria associationCriteria = listCriteria.createCriteria("dictIndemnityChildren");
   //        associationCriteria.addOrder(Order.desc("value"));
   //        listCriteria.addOrder(Order.asc("dParent.value"));
   listCriteria.createAlias("dictEstateChildren", "dictEstateChildren");
   listCriteria.addOrder(Order.asc("dictEstateChildren.value"));
   return (List<DictEstate>) listCriteria.list();
 }
  public List<Notification> findNotificationByCustomerId(final Long customerId, Object... params) {
    Criteria criteria = createDefaultCriteria(Notification.class);
    criteria.add(Restrictions.eq("customerId", customerId));

    criteria.addOrder(Order.asc("isChecked"));
    criteria.addOrder(Order.asc("createdDate"));

    @SuppressWarnings("unchecked")
    List<Notification> notifications = criteria.list();
    return notifications;
  }
 /** @see org.openmrs.api.db.LocationDAO#getAllLocations(boolean) */
 @SuppressWarnings("unchecked")
 public List<Location> getAllLocations(boolean includeRetired) {
   Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Location.class);
   if (!includeRetired) {
     criteria.add(Expression.eq("retired", false));
   } else {
     // push retired locations to the end of the returned list
     criteria.addOrder(Order.asc("retired"));
   }
   criteria.addOrder(Order.asc("name"));
   return criteria.list();
 }
 @Override
 public CommentModel findByIdWithCriteria(int commentId) {
   Session session = sessionFactory.getCurrentSession();
   Criteria cr = session.createCriteria(CommentModel.class);
   cr.add(Restrictions.eq("commentId", commentId));
   cr.add(Restrictions.isNotNull("commentTitle"));
   cr.add(Restrictions.in("commentTitle", new String[] {"abc", "def"}));
   cr.addOrder(Order.asc("commentId"));
   cr.addOrder(Order.desc("commentTitle"));
   CommentModel result = (CommentModel) cr.uniqueResult();
   return result;
 }
Exemple #25
0
  public List<Roles> takeRoles() {
    List<Roles> lst = null;
    String sortType = null;
    try {
      Session session = getSession();
      if (sort != null) {
        if (sort.indexOf('-') != -1) {
          sortType = "asc";
          sort = sort.substring(1);
        } else {
          sortType = "desc";
        }
      }

      Criteria cri = session.createCriteria(Roles.class);

      if (role != null) {

        if (role.getValue() != null && !"".equals(role.getValue())) {
          cri.add(Restrictions.eq("value", role.getValue()));
        }
        if (role.getName() != null && !"".equals(role.getName())) {
          cri.add(Restrictions.eq("name", role.getName()));
        }

        if (isactive != null) {
          cri.add(Restrictions.eq("isactive", "Y"));
        } else {
          cri.add(Restrictions.eq("isactive", "N"));
        }
      }

      if (sort != null) {
        if (sortType != null && sortType.equals("asc")) {
          cri.addOrder(Order.asc(sort).ignoreCase());
        } else if (sortType != null && sortType.equals("desc")) {
          cri.addOrder(Order.desc(sort).ignoreCase());
        }
      } else {
        cri.addOrder(Order.desc("lastUpdate").ignoreCase());
      }
      if (startval >= 0) {
        cri.setFirstResult(startval);
      }
      if (count >= 0) {
        cri.setMaxResults(count);
      }
      lst = cri.list();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return lst;
  }
Exemple #26
0
  public Pager findPager(Pager pager, Criteria criteria) {
    Assert.notNull(pager, "pager is required");
    Assert.notNull(criteria, "criteria is required");

    Integer pageNumber = pager.getPageNumber();
    Integer pageSize = pager.getPageSize();
    String searchBy = pager.getSearchBy();
    String keyword = pager.getKeyword();
    String orderBy = pager.getOrderBy();
    Pager.Order order = pager.getOrder();

    if (StringUtils.isNotEmpty(searchBy) && StringUtils.isNotEmpty(keyword)) {
      if (searchBy.contains(".")) {
        String alias = StringUtils.substringBefore(searchBy, ".");
        criteria.createAlias(alias, alias);
      }
      criteria.add(Restrictions.like(searchBy, "%" + keyword + "%"));
    }

    pager.setTotalCount(criteriaResultTotalCount(criteria));

    if (StringUtils.isNotEmpty(orderBy) && order != null) {
      if (order == Pager.Order.asc) {
        criteria.addOrder(Order.asc(orderBy));
      } else {
        criteria.addOrder(Order.desc(orderBy));
      }
    }

    ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
    if (!StringUtils.equals(orderBy, ORDER_LIST_PROPERTY_NAME)
        && ArrayUtils.contains(classMetadata.getPropertyNames(), ORDER_LIST_PROPERTY_NAME)) {
      criteria.addOrder(Order.asc(ORDER_LIST_PROPERTY_NAME));
      criteria.addOrder(Order.desc(CREATE_DATE_PROPERTY_NAME));
      if (StringUtils.isEmpty(orderBy) || order == null) {
        pager.setOrderBy(ORDER_LIST_PROPERTY_NAME);
        pager.setOrder(Pager.Order.asc);
      }
    } else if (!StringUtils.equals(orderBy, CREATE_DATE_PROPERTY_NAME)
        && ArrayUtils.contains(classMetadata.getPropertyNames(), CREATE_DATE_PROPERTY_NAME)) {
      criteria.addOrder(Order.desc(CREATE_DATE_PROPERTY_NAME));
      if (StringUtils.isEmpty(orderBy) || order == null) {
        pager.setOrderBy(CREATE_DATE_PROPERTY_NAME);
        pager.setOrder(Pager.Order.desc);
      }
    }

    criteria.setFirstResult((pageNumber - 1) * pageSize);
    criteria.setMaxResults(pageSize);

    pager.setResult(criteria.list());
    return pager;
  }
Exemple #27
0
  @SuppressWarnings("unchecked")
  public List<T> findByText(String searchText, String sortProp, boolean ascending) {
    List<Column> cols = HibernateUtil.getColumns(persistentClass.getName(), excludeDefault);
    Iterator<Column> it = cols.iterator();
    Criteria crit = getSession().createCriteria(persistentClass);
    Disjunction disjunction = Restrictions.disjunction();
    while (it.hasNext()) {
      Column col = it.next();
      String colName = col.getName();
      String propName = HibernateUtil.convertToHibernatePropertyName(colName);
      String type = HibernateUtil.getPropertyType(persistentClass, propName);
      if (type != null) {
        if (type.equals("integer") || type.equals("smallint")) {
          try {
            Integer.valueOf(searchText);
            Criterion criterium = Restrictions.eq(propName, Integer.valueOf(searchText));
            disjunction.add(criterium);
          } catch (NumberFormatException ex) {
          }
        } else if (type.equals("string")) {
          Criterion criterium = Restrictions.ilike(propName, searchText, MatchMode.ANYWHERE);
          disjunction.add(criterium);
        }
        /*else
            	if(type.equals("timestamp")){
            		Disjunction dis = Restrictions.disjunction();
           			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
           			try {
        	dis.add(Restrictions.eq(propName, format.parse(searchText)));
        } catch (ParseException e) {
        }
        try{
            			Integer.valueOf(searchText);
            			dis.add(Restrictions.sqlRestriction(
            					"YEAR(DATE("+colName+"))="+searchText+ " OR " +
               		"MONTH(DATE("+colName+"))="+searchText+ " OR " +
               		"DAY(DATE("+colName+"))="+searchText));
            		} catch(NumberFormatException ex) {
            		}
            		disjunction.add(dis);
            	}*/
      }
    }
    crit.add(disjunction);
    if (sortProp != null && !sortProp.equals("")) {
      if (ascending) crit.addOrder(Order.asc(sortProp));
      else crit.addOrder(Order.desc(sortProp));
    }

    return crit.list();
  }
 private Criteria getHBCriteria(Session session, SearchCriteria criteria) {
   Criteria newCriteria = session.createCriteria(WarrantyInformationType.class);
   if (criteria.getInternalId() != null) {
     newCriteria.add(Restrictions.eq("internalId", criteria.getInternalId()));
   }
   if ((criteria.ascending != null) && (criteria.ascending.contains("internalId")))
     newCriteria.addOrder(Order.asc("internalId"));
   else if ((criteria.descending != null) && (criteria.descending.contains("internalId")))
     newCriteria.addOrder(Order.desc("internalId"));
   if (criteria.getVersion() != null) {
     newCriteria.add(Restrictions.eq("version", criteria.getVersion()));
   }
   if ((criteria.ascending != null) && (criteria.ascending.contains("version")))
     newCriteria.addOrder(Order.asc("version"));
   else if ((criteria.descending != null) && (criteria.descending.contains("version")))
     newCriteria.addOrder(Order.desc("version"));
   if (criteria.getValue() != null) {
     newCriteria.add(Restrictions.eq("value", criteria.getValue()));
   }
   if ((criteria.ascending != null) && (criteria.ascending.contains("value")))
     newCriteria.addOrder(Order.asc("value"));
   else if ((criteria.descending != null) && (criteria.descending.contains("value")))
     newCriteria.addOrder(Order.desc("value"));
   if (criteria.getLanguageID() != null) {
     newCriteria.add(Restrictions.eq("languageID", criteria.getLanguageID()));
   }
   if ((criteria.ascending != null) && (criteria.ascending.contains("languageID")))
     newCriteria.addOrder(Order.asc("languageID"));
   else if ((criteria.descending != null) && (criteria.descending.contains("languageID")))
     newCriteria.addOrder(Order.desc("languageID"));
   return newCriteria;
 }
Exemple #29
0
  public List<Membro> getMembros(HashMap<String, String> formfields) {
    Criteria criteria = Persistence.getInstance().getSession().createCriteria(Membro.class);

    criteria.addOrder(Order.asc(this.getFirstAtributoDeOrdenacao()));
    criteria.addOrder(Order.asc(this.getSecondAtributoDeOrdenacao()));

    for (String campo : formfields.keySet()) {
      String like = "%" + formfields.get(campo) + "%";

      criteria.add(Restrictions.ilike(campo, like));
    }

    return criteria.list();
  }
Exemple #30
0
  private Criteria criteria(FullTextSession session) {
    final Class<?> cls = values.onlyTypes.get(0);
    Criteria criteria = session.createCriteria(cls);
    AnnotationCriteria ann = new AnnotationCriteria(criteria, values.fetchAnnotations);

    ids(criteria);
    ownerOrGroup(cls, criteria);
    createdOrModified(cls, criteria);
    annotatedBy(ann);
    annotatedBetween(ann);

    // annotatedWith
    if (values.onlyAnnotatedWith != null) {
      if (values.onlyAnnotatedWith.size() > 1) {
        throw new ApiUsageException(
            "HHH-879: "
                + "At the moment Hibernate cannot fulfill this request.\n"
                + "Please use only a single onlyAnnotatedWith "
                + "parameter when performing full text searches.");
      } else if (values.onlyAnnotatedWith.size() > 0) {
        if (!IAnnotated.class.isAssignableFrom(cls)) {
          // A non-IAnnotated object cannot have any
          // Annotations, and so our results are null
          return null; // EARLY EXIT !
        } else {
          for (Class<?> annCls : values.onlyAnnotatedWith) {
            SimpleExpression ofType = new TypeEqualityExpression("class", annCls);
            ann.getChild().add(ofType);
          }
        }
      } else {
        criteria.add(Restrictions.isEmpty("annotationLinks"));
      }
    }

    // orderBy
    if (values.orderBy.size() > 0) {
      for (int i = 0; i < values.orderBy.size(); i++) {
        String orderBy = values.orderBy.get(i);
        String orderWithoutMode = orderByPath(orderBy);
        boolean ascending = orderByAscending(orderBy);
        if (ascending) {
          criteria.addOrder(Order.asc(orderWithoutMode));
        } else {
          criteria.addOrder(Order.desc(orderWithoutMode));
        }
      }
    }
    return criteria;
  }