예제 #1
0
  public ArrayList<Candidate> getNumOfCandidateConstituency(Long constituency, String elecid) {
    Session session = null;
    ArrayList<String> numcon = new ArrayList<String>();
    ArrayList<Candidate> numcan = new ArrayList<Candidate>();
    Criteria ctr;
    try {
      session = getSessionFactory().openSession();
      ctr = session.createCriteria(Locations.class);
      ctr.add(Restrictions.eq("elecid", elecid));
      ctr.add(Restrictions.eq("constituency", constituency));
      if (ctr.list().size() > 0) {
        ctr = session.createCriteria(Candidate.class);
        ctr.add(Restrictions.eq("constituency", constituency));
        ctr.add(Restrictions.eq("validity", Candidate.ACCEPTED));
        for (int i = 0; ctr.list().size() > 0 && i < ctr.list().size(); i++)
          numcan.add((Candidate) ctr.list().get(i));
      }

    } catch (HibernateException e) {
      System.err.println("Error: file: LocationsDAO method: getNumOfCOnsti()");
    } finally {
      if (session != null) session.close();
    }

    return numcan;
  }
예제 #2
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;
  }
예제 #3
0
  public ArrayList<Election> getElectionByConstituency(Long constituency) {
    Session session = null;

    ArrayList<Election> eleclist = new ArrayList<Election>();
    Criteria ctr, tempctr;
    try {
      session = getSessionFactory().openSession();
      ctr = session.createCriteria(Locations.class);
      ctr.add(Restrictions.eq("constituency", constituency));
      for (int i = 0; ctr.list().size() > 0 && i < ctr.list().size(); i++) {
        tempctr = session.createCriteria(Election.class);
        tempctr.add(Restrictions.eq("validity", Election.NOTDONE));
        tempctr.add(Restrictions.idEq(((Locations) ctr.list().get(i)).getElecid()));
        tempctr.add(Restrictions.le("start", new Timestamp(new Date().getTime())));
        tempctr.add(Restrictions.ge("end", new Timestamp(new Date().getTime())));
        if (tempctr.list().size() > 0) eleclist.add((Election) tempctr.list().get(0));
      }

    } catch (HibernateException e) {
      System.err.println("Error: file: LocationsDAO method: getNumOfCOnsti()");
    } finally {
      if (session != null) session.close();
    }

    return eleclist;
  }
예제 #4
0
 public HashMap getAllRateCodes() {
   /**
    * Requires - Modifies - Effects -
    *
    * @throws -
    */
   Criteria objCriteria = null;
   Session objSession = null;
   Integer totRecordCount = null;
   List objList = null;
   HashMap hmResult = new HashMap();
   try {
     logger.info("GETTING ALL RATE CODES");
     objSession = HibernateUtil.getSession();
     objCriteria = objSession.createCriteria(RateCodesVO.class);
     totRecordCount = new Integer(objCriteria.list().size());
     objList = objCriteria.list();
     hmResult.put("TotalRecordCount", totRecordCount);
     hmResult.put("Records", objList);
     logger.info("GOT ALL RATE CODES");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET ALL RATE CODES", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return hmResult;
 }
  @Test
  @TestForIssue(jiraKey = "HHH-7767")
  public void testCriteriaRestrictionOnIdManyToOne() {
    Session s = openSession();
    s.beginTransaction();

    s.createQuery("from Course c join c.students cs join cs.student s where s.name = 'Foo'").list();

    Criteria criteria = s.createCriteria(Course.class);
    criteria
        .createCriteria("students")
        .createCriteria("student")
        .add(Restrictions.eq("name", "Foo"));
    criteria.list();

    Criteria criteria2 = s.createCriteria(Course.class);
    criteria2.createAlias("students", "cs");
    criteria2.add(Restrictions.eq("cs.value", "Bar"));
    criteria2.createAlias("cs.student", "s");
    criteria2.add(Restrictions.eq("s.name", "Foo"));
    criteria2.list();

    s.getTransaction().commit();
    s.close();
  }
  public Establishment getEstablishment(int idEstablishment) {
    Session session = null;
    Transaction transaction = null;
    Establishment establishment = null;

    try {
      session = sessionFactory.getCurrentSession();
      transaction = session.beginTransaction();
      Criteria cr = session.createCriteria(Establishment.class);
      cr.add(Restrictions.eq("idEstablishment", idEstablishment));
      if (!cr.list().isEmpty()) {
        establishment = (Establishment) cr.list().get(0);
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
      if (transaction != null) {
        transaction.rollback();
      }
      e.printStackTrace();
    } finally {
      if (session != null && session.isOpen()) session.close();
    }

    return establishment;
  }
  public List getWeblogEntries(WeblogCategoryData cat, boolean subcats) throws RollerException {
    try {
      Session session = ((HibernatePersistenceStrategy) this.strategy).getSession();
      List entries = new LinkedList();

      if (subcats) {
        // Get entries in subcategories
        Criteria assocsQuery = session.createCriteria(WeblogCategoryAssoc.class);
        assocsQuery.add(Expression.eq("ancestorCategory", cat));
        Iterator assocs = assocsQuery.list().iterator();
        while (assocs.hasNext()) {
          WeblogCategoryAssoc assoc = (WeblogCategoryAssoc) assocs.next();
          Criteria entriesQuery = session.createCriteria(WeblogEntryData.class);
          entriesQuery.add(Expression.eq("category", assoc.getCategory()));
          Iterator entryIter = entriesQuery.list().iterator();
          while (entryIter.hasNext()) {
            WeblogEntryData entry = (WeblogEntryData) entryIter.next();
            entries.add(entry);
          }
        }
      }

      // Get entries in category
      Criteria entriesQuery = session.createCriteria(WeblogEntryData.class);
      entriesQuery.add(Expression.eq("category", cat));
      Iterator entryIter = entriesQuery.list().iterator();
      while (entryIter.hasNext()) {
        WeblogEntryData entry = (WeblogEntryData) entryIter.next();
        entries.add(entry);
      }
      return entries;
    } catch (HibernateException e) {
      throw new RollerException(e);
    }
  }
  @GlobalDBOpenCloseAndUserPrivilages
  public Map getUserTypeSize(
      Session session,
      HttpServletRequest request,
      HttpServletResponse response,
      String LoggedInRegion,
      String LoggedInUser) {
    Map resultMap = new HashMap();
    String isAccountModule = "No";
    Map financialYearMap = new LinkedHashMap();
    financialYearMap.put("0", "--Select--");
    UserViewModel userObj = (UserViewModel) request.getSession(false).getAttribute("userDetails");

    Criteria rcCriteria = session.createCriteria(Useroperatingrights.class);
    rcCriteria.add(Restrictions.sqlRestriction("userid = '" + userObj.getUserid() + "'"));
    rcCriteria.add(Restrictions.sqlRestriction("accessright is true"));
    rcCriteria.addOrder(Order.asc("usertypeid"));
    List rcList = rcCriteria.list();
    resultMap.put("typesize", rcList.size());

    Criteria fyearsCriteria = session.createCriteria(Accountingyear.class);
    List fyearsList = fyearsCriteria.list();
    if (fyearsList.size() > 0) {
      for (int i = 0; i < fyearsList.size(); i++) {
        Accountingyear accountingyearObj = (Accountingyear) fyearsList.get(i);
        financialYearMap.put(
            accountingyearObj.getId(),
            (accountingyearObj.getStartyear() + "-" + accountingyearObj.getEndyear()));
      }
    }
    resultMap.put("financialYearMap", financialYearMap);

    if (rcList.size() == 1) {
      Useroperatingrights useroperatingrightsObj = (Useroperatingrights) rcList.get(0);

      Criteria privileageCriteria = session.createCriteria(Menuprivilages.class);
      privileageCriteria.add(
          Restrictions.sqlRestriction("usertype = " + useroperatingrightsObj.getUsertypeid()));
      privileageCriteria.add(Restrictions.sqlRestriction("accessright is true"));
      List privileageList = privileageCriteria.list();
      if (privileageList.size() > 0) {
        for (int j = 0; j < privileageList.size(); j++) {
          Menuprivilages menuprivilagesObj = (Menuprivilages) privileageList.get(j);
          //
          // System.out.println("menuprivilagesObj.getMenumaster().getGrouptype()==" +
          // menuprivilagesObj.getMenumaster().getGrouptype());
          if (menuprivilagesObj.getMenumaster().getGrouptype() == null) {
          } else if (menuprivilagesObj.getMenumaster().getGrouptype() == 'A') {
            isAccountModule = "Yes";
            break;
          }
        }
      }
    }
    resultMap.put("isAccountModule", isAccountModule);

    return resultMap;
  }
 public List<FamiliarJugador> buscarPorRepresentante(Familiar d) {
   Session session = getSession();
   Transaction tx = session.beginTransaction();
   Criteria c = getSession().createCriteria(FamiliarJugador.class);
   c.add(Restrictions.eq("familiar", d)).list();
   if (c.list().isEmpty()) {
     return null;
   } else return c.list();
 }
예제 #10
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;
  }
예제 #11
0
  @Override
  public String execute() throws Exception {
    String name = this.getRequest().getParameter("name");
    String value = this.getRequest().getParameter("value");
    String type = this.getRequest().getParameter("type");
    String policy = this.getRequest().getParameter("policy");
    String enable = this.getRequest().getParameter("enable");

    Session session = SessionFactorySingle.getSessionFactory().openSession();
    session.beginTransaction();

    Criteria criteria = session.createCriteria(TypeDeviceFilter.class);
    criteria.add(Restrictions.eq("id", Integer.valueOf(type)));
    List<TypeDeviceFilter> typeDeviceFilters_array = criteria.list();
    TypeDeviceFilter typeDeviceFilter = typeDeviceFilters_array.get(0);

    criteria = session.createCriteria(DeviceFilter.class);
    criteria.add(Restrictions.eq("name", name));
    List<DeviceFilter> deviceFilters = (List<DeviceFilter>) criteria.list();

    DeviceFilter deviceFilter;
    if (deviceFilters.size() > 0) {
      deviceFilter = deviceFilters.get(0);
      deviceFilter.setName(name);
      deviceFilter.setValue(value);
      deviceFilter.setType(typeDeviceFilter);
      deviceFilter.setPolicy(Boolean.valueOf(policy));
      deviceFilter.setEnable(Boolean.valueOf(enable));
    } else {
      deviceFilter = new DeviceFilter(name, value, typeDeviceFilter, Boolean.valueOf(policy));
    }

    session.save(deviceFilter);
    session.getTransaction().commit();

    criteria = session.createCriteria(TroubleList.class);
    criteria.add(Restrictions.eq("name", "main"));
    TroubleList troubleList = (TroubleList) criteria.list().get(0);
    troubleList.getFilters().add(deviceFilter);

    session.beginTransaction();

    session.save(troubleList);
    session.getTransaction().commit();

    session.flush();
    session.close();

    ManagerMainDeviceFilter.getInstance().addNewDeviceInputFilter(deviceFilter);

    return null;
  }
예제 #12
0
 public List<User> getStudentUserDataList(Integer userID, String status) {
   Criteria criteria = getSession().createCriteria(User.class);
   criteria.add(Restrictions.eq("userId", userID));
   List<User> list = criteria.list();
   closeSession();
   if (status.equals("user")) {
     Criteria criteria1 = getSession().createCriteria(UniversityFacultyMajor.class);
     criteria1.add(Restrictions.eq("uniFacMajId", list.get(0).getUniFacMajId()));
     List<UniversityFacultyMajor> list1 = criteria1.list();
     closeSession();
     list.get(0).setUniversityFacultyMajor(list1.get(0));
   }
   return list;
 }
예제 #13
0
  public Map<String, Object> lista(Map<String, Object> params) {
    log.debug("Buscando lista de Temporada Colportor con params {}", params);
    if (params == null) {
      params = new HashMap<>();
    }
    if (!params.containsKey(Constantes.CONTAINSKEY_MAX)) {
      params.put(Constantes.CONTAINSKEY_MAX, 10);
    } else {
      params.put(
          Constantes.CONTAINSKEY_MAX,
          Math.min((Integer) params.get(Constantes.CONTAINSKEY_MAX), 100));
    }
    if (params.containsKey(Constantes.CONTAINSKEY_PAGINA)) {
      Long pagina = (Long) params.get(Constantes.CONTAINSKEY_PAGINA);
      Long offset = (pagina - 1) * (Integer) params.get(Constantes.CONTAINSKEY_MAX);
      params.put(Constantes.CONTAINSKEY_OFFSET, offset.intValue());
    }
    if (!params.containsKey(Constantes.CONTAINSKEY_OFFSET)) {
      params.put(Constantes.CONTAINSKEY_OFFSET, 0);
    }
    Criteria criteria = currentSession().createCriteria(TemporadaColportor.class);
    Criteria countCriteria = currentSession().createCriteria(TemporadaColportor.class);
    if (params.containsKey(Constantes.CONTAINSKEY_FILTRO)) {
      String filtro = (String) params.get(Constantes.CONTAINSKEY_FILTRO);
      filtro = "%" + filtro + "%";
      Disjunction propiedades = Restrictions.disjunction();
      propiedades.add(Restrictions.ilike("status", filtro));

      criteria.add(propiedades);
      countCriteria.add(propiedades);
    }
    if (params.containsKey(Constantes.CONTAINSKEY_ORDER)) {
      String campo = (String) params.get(Constantes.CONTAINSKEY_ORDER);
      if (params.get(Constantes.CONTAINSKEY_SORT).equals(Constantes.CONTAINSKEY_SORT)) {
        criteria.addOrder(Order.desc(campo));
      } else {
        criteria.addOrder(Order.asc(campo));
      }
    }
    if (!params.containsKey(Constantes.CONTAINSKEY_REPORTE)) {
      criteria.setFirstResult((Integer) params.get(Constantes.CONTAINSKEY_OFFSET));
      criteria.setMaxResults((Integer) params.get(Constantes.CONTAINSKEY_MAX));
    }
    params.put(Constantes.CONTAINSKEY_TEMPORADACOLPORTORES, criteria.list());
    countCriteria.setProjection(Projections.rowCount());
    params.put(Constantes.CONTAINSKEY_CANTIDAD, (Long) countCriteria.list().get(0));

    return params;
  }
예제 #14
0
  @Override
  @SuppressWarnings("unchecked")
  public void cleanupDatabase() {
    Criteria allTagEntriesCrit = getSession().createCriteria(RecipeCategoryEntry.class);
    List<RecipeCategoryEntry> usedTagEntries = allTagEntriesCrit.list();

    Set<Long> usedTagIds = new HashSet<Long>();

    for (RecipeCategoryEntry usedTag : usedTagEntries) {
      usedTagIds.add(usedTag.getCategory().getId());
    }

    Criteria unusedTagsCrit = getSession().createCriteria(RecipeCategory.class);
    unusedTagsCrit.add(Restrictions.not(Restrictions.in("id", usedTagIds)));
    unusedTagsCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    Criteria allIngrEntriesCrit = getSession().createCriteria(RecipeIngredientEntry.class);
    List<RecipeIngredientEntry> usedIngrEntries = allIngrEntriesCrit.list();

    Set<Long> usedIngrIds = new HashSet<Long>();
    Set<Long> usedIngrGrpIds = new HashSet<Long>();

    for (RecipeIngredientEntry usedIngr : usedIngrEntries) {
      usedIngrIds.add(usedIngr.getIngredient().getId());
      usedIngrGrpIds.add(usedIngr.getGroup().getId());
    }

    Criteria unusedIngrsCrit = getSession().createCriteria(RecipeIngredient.class);
    unusedIngrsCrit.add(Restrictions.not(Restrictions.in("id", usedIngrIds)));
    unusedIngrsCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    Criteria unusedIngrGrpsCrit = getSession().createCriteria(RecipeIngredientGroup.class);
    unusedIngrGrpsCrit.add(Restrictions.not(Restrictions.in("id", usedIngrGrpIds)));
    unusedIngrGrpsCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    /** ************* */
    for (Object objToDel : unusedTagsCrit.list()) {
      getSession().delete(objToDel);
    }

    for (Object objToDel : unusedIngrsCrit.list()) {
      getSession().delete(objToDel);
    }

    for (Object objToDel : unusedIngrGrpsCrit.list()) {
      getSession().delete(objToDel);
    }
  }
  /**
   * The 'findConfigurations' function will return a list of configurations based on a search term
   * passed in. The function will search configurations on the following fields configName, orgName
   * and messageTypeName @Table configurations
   *
   * @param searchTerm Will hold the term used search configurations on
   * @return This function will return a list of configuration objects
   */
  @Override
  @SuppressWarnings("unchecked")
  public List<configuration> findConfigurations(String searchTerm) {

    if (searchTerm != "") {
      // get a list of organization id's that match the term passed in
      List<Integer> orgIdList = new ArrayList<Integer>();
      Criteria findOrgs = sessionFactory.getCurrentSession().createCriteria(Organization.class);
      findOrgs.add(Restrictions.like("orgName", "%" + searchTerm + "%"));
      List<Organization> orgs = findOrgs.list();

      for (Organization org : orgs) {
        orgIdList.add(org.getId());
      }

      // get a list of message type id's that match the term passed in
      List<Integer> msgTypeIdList = new ArrayList<Integer>();
      Criteria findMsgTypes = sessionFactory.getCurrentSession().createCriteria(messageType.class);
      findMsgTypes.add(Restrictions.like("name", "%" + searchTerm + "%"));
      List<messageType> msgTypes = findMsgTypes.list();

      for (messageType msgType : msgTypes) {
        msgTypeIdList.add(msgType.getId());
      }

      Criteria criteria = sessionFactory.getCurrentSession().createCriteria(configuration.class);

      if (orgIdList.size() == 0) {
        orgIdList.add(0);
      }
      if (msgTypeIdList.size() == 0) {
        msgTypeIdList.add(0);
      }

      criteria
          .add(
              Restrictions.or(
                  Restrictions.in("orgId", orgIdList),
                  Restrictions.in("messageTypeId", msgTypeIdList)))
          .addOrder(Order.desc("dateCreated"));

      return criteria.list();
    } else {
      Criteria criteria = sessionFactory.getCurrentSession().createCriteria(configuration.class);
      criteria.addOrder(Order.desc("dateCreated"));
      return criteria.list();
    }
  }
 @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();
 }
예제 #17
0
  /**
   * Tìm kiếm nhanh
   *
   * @param c Tiêu chí tìm kiếm
   * @return Danh sách các điện thoại thỏa tiêu chí tìm kiếm
   */
  @SuppressWarnings("unchecked")
  public List<DienThoai> quickSearch(QuickSearchCriteria c) {

    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(DienThoai.class);

    if (c.getIdHangDienThoai() > 0) {
      Criterion manufacture = Restrictions.eq("hangDienThoai.id", c.getIdHangDienThoai());
      criteria.add(manufacture);
    }

    if (c.getTenDienThoai() != null) {
      Criterion name = Restrictions.like("ten", "%" + c.getTenDienThoai() + "%");
      criteria.add(name);
    }

    if (c.getGiaTu() >= 0.0) {
      Criterion minPrice = Restrictions.ge("giaHienHanh", c.getGiaTu());
      criteria.add(minPrice);
    }

    if (c.getGiaDen() >= 0.0) {
      Criterion maxPrice = Restrictions.le("giaHienHanh", c.getGiaDen());
      criteria.add(maxPrice);
    }
    criteria.add(Restrictions.eq("xoa", false));

    return criteria.list();
  }
예제 #18
0
  /**
   * Tìm kiếm nhanh
   *
   * @param idHangDienThoai id của HangDienThoai.
   * @param ten tên DienThoai.
   * @param giaTu giá chặn dưới.
   * @param giaDen giá chặn trên.
   * @return Danh sách DienThoai thỏa tiêu chí tìm kiếm.
   */
  @SuppressWarnings("unchecked")
  public List<DienThoai> quickSearch(int idHangDienThoai, String ten, double giaTu, double giaDen) {

    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(DienThoai.class);

    if (idHangDienThoai > 0) {
      Criterion manufacture = Restrictions.eq("hangDienThoai.id", idHangDienThoai);
      criteria.add(manufacture);
    }

    if (ten != null) {
      Criterion name = Restrictions.like("ten", "%" + ten + "%");
      criteria.add(name);
    }

    if (giaTu >= 0.0) {
      Criterion minPrice = Restrictions.ge("giaHienHanh", giaTu);
      criteria.add(minPrice);
    }

    if (giaDen >= 0.0) {
      Criterion maxPrice = Restrictions.le("giaHienHanh", giaDen);
      criteria.add(maxPrice);
    }
    criteria.add(Restrictions.eq("xoa", false));

    return criteria.list();
  }
  @Override
  @SuppressWarnings("unchecked")
  public List<ProgramInstance> getByStatus(
      ProgramStatus status,
      Program program,
      Collection<Integer> orgunitIds,
      Date startDate,
      Date endDate,
      Integer min,
      Integer max) {
    Criteria criteria =
        getCriteria(
                Restrictions.eq("program", program),
                Restrictions.between("enrollmentDate", startDate, endDate))
            .createAlias("entityInstance", "entityInstance")
            .createAlias("entityInstance.organisationUnit", "organisationUnit")
            .add(Restrictions.in("organisationUnit.id", orgunitIds))
            .add(Restrictions.eq("status", status));

    if (min != null) {
      criteria.setFirstResult(min);
    }

    if (max != null) {
      criteria.setMaxResults(max);
    }

    return criteria.list();
  }
 public List getAll() {
   List values = null;
   Session session = getSession();
   Criteria allValues = session.createCriteria(CorporateRegistrationSchemeType.class);
   values = allValues.list();
   return values;
 }
예제 #21
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;
  }
예제 #22
0
 public List<Consulta> pesquisarTodosConsultaData(Date data) throws Exception {
   List<Consulta> lista = null;
   Criteria cr = session.createCriteria(Consulta.class).add(Restrictions.eq("dataConsulta", data));
   lista = (ArrayList) cr.list();
   closeSession();
   return lista;
 }
예제 #23
0
 public List<Consulta> pesquisarTodosConsulta() throws Exception {
   List<Consulta> lista = null;
   Criteria cr = session.createCriteria(Consulta.class);
   lista = (ArrayList) cr.list();
   closeSession();
   return lista;
 }
예제 #24
0
  @Override
  public List<Role> getAllRoles() {

    Session session = SessionFactoryProvider.getSessionFactory().openSession();
    Transaction tx = null;
    List<Role> allRoles = new ArrayList<Role>();

    try {
      tx = session.beginTransaction();
      Criteria criteria = session.createCriteria(Role.class);
      List<Role> roles = criteria.list();

      for (Role r : roles) {
        allRoles.add(r);
      }

      tx.commit();
    } catch (HibernateException e) {
      if (tx != null) {
        e.printStackTrace();
      }
    } finally {
      session.close();
    }

    return allRoles;
  }
예제 #25
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;
 }
예제 #26
0
  @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();
    }
  }
예제 #27
0
 // 此方法用于动态条件查询
 public Collection find(Product product) throws ManagerProductException {
   Session session = null;
   Transaction tran = null;
   Collection list = null;
   try {
     session = HibernateUtils.getSession();
     tran = session.beginTransaction();
     Criteria crit = session.createCriteria(Product.class);
     if (product.getAuthor().equals("")) {
       crit.add(Restrictions.like("author", "%"));
     } else {
       crit.add(Restrictions.like("author", "%" + product.getAuthor() + "%"));
     }
     if (product.getName().equals("")) {
       crit.add(Restrictions.like("name", "%"));
     } else {
       crit.add(Restrictions.like("name", "%" + product.getName() + "%"));
     }
     if (product.getPublish().equals("")) {
       crit.add(Restrictions.like("publish", "%"));
     } else {
       crit.add(Restrictions.like("publish", "%" + product.getPublish() + "%"));
     }
     list = crit.list();
     tran.commit();
   } catch (Exception e) {
     e.printStackTrace();
     tran.rollback();
   } finally {
     session.close();
     return list;
   }
 }
예제 #28
0
  @SuppressWarnings("unchecked")
  public static java.util.List<Object> getListData(
      Class<?> classBean, String strKey1, Object value1, String strKey2, Object value2) {
    java.util.List<Object> result = new java.util.ArrayList<Object>();
    Session session = null;
    try {
      session = sessionFactory.openSession();
      Transaction tx = session.beginTransaction();

      Criteria criteria = session.createCriteria(classBean);
      if (strKey1 != null) {
        criteria.add(Restrictions.like(strKey1, value1));
      }
      if (strKey2 != null) {
        criteria.add(Restrictions.like(strKey2, value2));
      }

      result = criteria.list();

      tx.commit();

    } finally {
      if (session != null) {
        session.close();
      }
    }
    return result;
  }
예제 #29
0
 public Collection getAllRateCodes(int tdspId) {
   /**
    * Requires - Modifies - Effects -
    *
    * @throws -
    */
   Criteria objCriteria = null;
   Session objSession = null;
   List objList = null;
   try {
     logger.info("GETTING ALL RATE CODES BY TDSP ID");
     objSession = HibernateUtil.getSession();
     objCriteria =
         objSession
             .createCriteria(RateCodesVO.class)
             .add(Restrictions.eq("tdsp.tdspIdentifier", new Integer(tdspId)));
     objCriteria.addOrder(Order.asc("rateCode"));
     objList = objCriteria.list();
     logger.info("GOT ALL RATE CODES BY TDSP ID");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET ALL RATE CODES BY TDSP ID", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return objList;
 }
예제 #30
0
 public List<Consulta> pesquisarConsultaPorPaciente(Paciente paciente) throws Exception {
   List<Consulta> lista = null;
   Criteria cr = session.createCriteria(Consulta.class).add(Restrictions.eq("paciente", paciente));
   lista = (ArrayList) cr.list();
   closeSession();
   return lista;
 }