Example #1
0
 @SuppressWarnings("unchecked")
 public static List<Object> listCurrentRecords(int objectType) {
   // TODO by the candidate
   /*
    * This method is called when you open any list screen and should return
    * all records of the specified type
    */
   Session session = sessionFactory.getCurrentSession();
   List<Object> objList = new ArrayList<Object>();
   try {
     session.beginTransaction();
     switch (objectType) {
       case TYPE_CUSTOMER:
         objList = session.createCriteria(Customer.class).list();
         break;
       case TYPE_PRODUCT:
         objList = session.createCriteria(Product.class).list();
         break;
       case TYPE_SALESORDER:
         Set<SalesOrder> set =
             new HashSet<SalesOrder>(session.createCriteria(SalesOrder.class).list());
         objList = new ArrayList<Object>(set);
         break;
       default:
         break;
     }
     session.getTransaction().commit();
   } catch (HibernateException e) {
     logger.error("Error while retrieving records", e);
     session.getTransaction().rollback();
   }
   return objList;
 }
  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);
    }
  }
  @Test
  public void testSimpleCrossTxnWork() {
    Session session1 = injector.getInstance(SessionFactory.class).openSession();
    ManagedSessionContext.bind(session1);
    HibernateTestEntity entity =
        injector
            .getInstance(ManualLocalTransactionsWithCustomMatchersTest.TransactionalObject.class)
            .runOperationInTxn();
    injector
        .getInstance(ManualLocalTransactionsWithCustomMatchersTest.TransactionalObject.class)
        .runOperationInTxn2();

    assert injector.getInstance(Session.class).contains(entity)
        : "Session appears to have been closed across txns!";
    session1.close();

    // try to query them back out

    Session session = injector.getInstance(SessionFactory.class).openSession();
    assert null
        != session
            .createCriteria(HibernateTestEntity.class)
            .add(Expression.eq("text", UNIQUE_TEXT))
            .uniqueResult();
    assert null
        != session
            .createCriteria(HibernateTestEntity.class)
            .add(Expression.eq("text", UNIQUE_TEXT_2))
            .uniqueResult();
    session.close();
  }
Example #4
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;
  }
  @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();
  }
Example #6
0
  @SuppressWarnings("unchecked")
  public List<Dap> getDaps() {

    if (dapExample != null) {
      Example example =
          Example.create(dapExample).excludeFalse().ignoreCase().enableLike(MatchMode.ANYWHERE);
      return session.createCriteria(Dap.class).add(example).list();
    } else if (searchText != null && searchText.trim().length() > 0) {
      FullTextSession fullTextSession = Search.getFullTextSession(sessionManager.getSession());
      try {
        fullTextSession.createIndexer().startAndWait();
      } catch (java.lang.InterruptedException e) {
        logger.warn("Lucene Indexing was interrupted by something " + e);
      }

      QueryBuilder qb =
          fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Dap.class).get();
      org.apache.lucene.search.Query luceneQuery =
          qb.keyword().onFields("name").matching(searchText).createQuery();

      return fullTextSession.createFullTextQuery(luceneQuery, Dap.class).list();
    } else {
      // default - unfiltered - all entitites list
      return session.createCriteria(Dap.class).list();
    }
  }
  @GET
  @SuppressWarnings("unchecked")
  public ResultList<InfoClinica> list(
      @QueryParam("count") Integer count,
      @QueryParam("page") Integer page,
      @QueryParam("search.valor") String valor) {

    Session session = (Session) em.getDelegate();
    Criteria criteria = session.createCriteria(getType());
    Criteria countCriteria = session.createCriteria(getType());

    criteria.addOrder(Order.asc("valor"));

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

    if (count != null && page != null) {
      criteria.setFirstResult((page - 1) * count);
    }

    if (valor != null) {
      criteria.add(Restrictions.ilike("nome", valor, ANYWHERE));
      countCriteria.add(Restrictions.ilike("nome", valor, ANYWHERE));
    }

    List<InfoClinica> list = criteria.list();
    Long totalResults = (Long) countCriteria.setProjection(Projections.rowCount()).uniqueResult();

    return new ResultList<>(list, page, count, totalResults.intValue());
  }
Example #8
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;
  }
Example #9
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;
  }
  @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();
  }
  @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;
  }
 @Override
 public Query createQuery(Class type, String alias) {
   final PersistentEntity persistentEntity =
       getMappingContext().getPersistentEntity(type.getName());
   Session currentSession = getHibernateTemplate().getSessionFactory().getCurrentSession();
   final Criteria criteria =
       alias != null
           ? currentSession.createCriteria(type, alias)
           : currentSession.createCriteria(type);
   getHibernateTemplate().applySettings(criteria);
   return new HibernateQuery(criteria, this, persistentEntity);
 }
Example #13
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

      String su = request.getParameter("subid");

      int i = 1;

      Session s = NewHibernateUtil.getSessionFactory().openSession();
      Transaction t = s.beginTransaction();

      Criteria cr = s.createCriteria(Subject.class);
      cr.add(Restrictions.eq("idsubject", Integer.parseInt(su)));
      Subject sab = (Subject) cr.uniqueResult();
      Subject subt = (Subject) s.load(Subject.class, sab.getIdsubject());

      Criteria c = s.createCriteria(School.class);
      c.add(Restrictions.eq("subject", subt));

      JSONArray json = new JSONArray();
      Map m = new HashMap();

      List<School> list = c.list();

      for (School school : list) {
        m.put("schoolName", school.getSchoolName());
        m.put("grade11", school.getGrade11());
        m.put("grade10", school.getGrade10());
        m.put("grade9", school.getGrade9());
        m.put("subject", school.getSubject().getSubjectName());

        json.add(m);

        m = null;
        m = new HashMap();

        out.write(json.toJSONString());

        //                out.write("<tr>" + school.getSchoolName() + "</tr>");
        //                out.write("<tr>" + school.getGrade11() + "</tr>");
        //                out.write("<tr>" + school.getGrade10() + "</tr>");
        //                out.write("<tr>" + school.getGrade9() + "</tr>");
        //                out.write("<tr>" + school.getSubject().getSubjectName() + "</tr>");
      }

    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html;charset=UTF-8");
   PrintWriter out = response.getWriter();
   HttpSession httpSession = request.getSession();
   String answer;
   Session hibSession = HibernateUtil.getSession();
   hibSession.beginTransaction();
   int param1 = Integer.parseInt(request.getParameter("param1"));
   List clients =
       hibSession.createCriteria(Client.class).add(Restrictions.eq("client_id", param1)).list();
   Client client = (Client) clients.get(0);
   List agreements =
       hibSession.createCriteria(Agreement.class).add(Restrictions.eq("client", client)).list();
   Collections.sort(
       agreements,
       new Comparator<Agreement>() {
         @Override
         public int compare(Agreement lhs, Agreement rhs) {
           return -1 * lhs.getDate_written().compareTo(rhs.getDate_written());
         }
       });
   List payments =
       hibSession.createCriteria(Payment.class).add(Restrictions.eq("client", client)).list();
   Collections.sort(
       payments,
       new Comparator<Payment>() {
         @Override
         public int compare(Payment lhs, Payment rhs) {
           return -1 * lhs.getPaym_date().compareTo(rhs.getPaym_date());
         }
       });
   Gson gson = new Gson();
   String jsonClient = gson.toJson(clients.get(0), Client.class);
   String jsonAgreements = gson.toJson(agreements);
   String jsonPayments = gson.toJson(payments);
   answer =
       "{ \"client\" : "
           + jsonClient
           + ", "
           + "\"agreements\" : "
           + jsonAgreements
           + ", "
           + "\"payments\" : "
           + jsonPayments
           + "}";
   hibSession.beginTransaction().commit();
   hibSession.close();
   if (clients.size() != 1) answer = FAILURE;
   response.getWriter().write(answer);
 }
Example #15
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();
  }
Example #16
0
 public static Group findByOrgAndName(Organisation org, String name, Session session) {
   Criteria crit = session.createCriteria(Group.class);
   crit.setCacheable(true);
   crit.add(Restrictions.eq("organisation", org));
   crit.add(Restrictions.eq("name", name));
   return (Group) crit.uniqueResult();
 }
Example #17
0
 public static List<Group> findByOrg(Organisation org, Session session) {
   Criteria crit = session.createCriteria(Group.class);
   crit.setCacheable(true);
   crit.add(Restrictions.eq("organisation", org));
   crit.addOrder(Order.asc("name"));
   return DbUtils.toList(crit, Group.class);
 }
 public List getAll() {
   List values = null;
   Session session = getSession();
   Criteria allValues = session.createCriteria(CorporateRegistrationSchemeType.class);
   values = allValues.list();
   return values;
 }
Example #19
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;
 }
Example #20
0
 public List<Consulta> pesquisarTodosConsulta() throws Exception {
   List<Consulta> lista = null;
   Criteria cr = session.createCriteria(Consulta.class);
   lista = (ArrayList) cr.list();
   closeSession();
   return lista;
 }
 // 此方法用于动态条件查询
 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;
   }
 }
Example #22
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();
  }
Example #23
0
  public User getDetail(String login, Session session) {
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.eq("login", login));

    User user = (User) criteria.uniqueResult();
    return user;
  }
  public static void main(String[] args) {
    System.out.println("Testing Hibernate Utility Class");
    Session session = HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();
    Profile u = new Profile();
    u.setCreateDate(new Date());
    u.setFirstName("firstName");
    u.setLastName("lastNAme");
    u.setPassword("password1");

    session.save(u);
    u = new Profile();
    u.setCreateDate(new Date());
    u.setFirstName("firstName");
    u.setLastName("lastNAme");
    u.setPassword("password1");
    session.save(u);

    List all = session.createCriteria(Profile.class).list();

    System.out.println(all);
    // session.delete(cat);

    session.getTransaction().commit();
  }
  @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;
  }
Example #26
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;
 }
Example #27
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;
 }
Example #28
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;
 }
 @Override
 public List<Statistics> getByBookId(int id) {
   Session session = sessionFactory.getCurrentSession();
   Criteria criteria = session.createCriteria(Statistics.class);
   List<Statistics> statistics = criteria.add(Restrictions.eq("book.id", id)).list();
   return statistics;
 }
Example #30
0
 public Consulta pesquisarConsultaPorId(long id) throws Exception {
   Consulta c = new Consulta();
   Criteria cr = session.createCriteria(Consulta.class).add(Restrictions.eq("idConsulta", id));
   c = (Consulta) cr.uniqueResult();
   closeSession();
   return c;
 }