Example #1
0
 public List<User> getUserSearchResults(int topicId) {
   // TODO Auto-generated method stub
   List<User> userArr = new ArrayList<User>();
   Session session = sessionFactory.openSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Query query1 = session.createQuery("select userId from UserTopic where topicId = :topicId");
     query1.setString("topicId", String.valueOf(topicId));
     Query query2 = session.createQuery("from User where userId in (:userList)");
     query2.setParameterList("userList", query1.list());
     userArr = query2.list();
     /*for(Topic topic : topicArr){
     	System.out.println("Topic Description----"+topic.getTopicDescription());
     	System.out.println("Topic Id----"+topic.getTopicId());
     }*/
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
   return userArr;
 }
  @Override
  public List<Puesto> findByName(String nombre) {

    if (nombre == null) {

      Session session = sessionFactory.getCurrentSession();

      Query query = session.createQuery("SELECT puesto FROM Puesto puesto");

      List<Puesto> puestos = query.list();

      return puestos;

    } else {

      Session session = sessionFactory.getCurrentSession();

      Query query = session.createQuery("SELECT puesto FROM Puesto puesto WHERE nombre LIKE ?");

      query.setString(0, "%" + nombre + "%");

      List<Puesto> puestos = query.list();

      return puestos;
    }
  }
  @Test
  @SuppressWarnings("unchecked")
  public void testEntitiesInsertedInCurrentSessionAreFoundByNativeQuery() throws Exception {
    OgmSession session = openSession();
    Transaction transaction = session.beginTransaction();

    String nativeQuery = "{ name : 'Her Voice' }";

    Query query = session.createNativeQuery(nativeQuery).addEntity(OscarWildePoem.class);

    List<OscarWildePoem> result = query.list();
    assertThat(result).isEmpty();

    OscarWildePoem voice = new OscarWildePoem(4L, "Her Voice", "Oscar Wilde");
    session.persist(voice);

    result = query.list();
    assertThat(result).onProperty("id").containsExactly(4L);

    transaction.commit();

    transaction = session.beginTransaction();
    session.delete(voice);
    transaction.commit();

    session.close();
  }
Example #4
0
  public List<IpPoolManagement> findpublicIpsToPurchaseByVirtualDatacenter(
      final Integer vdcId,
      Integer startwith,
      final Integer limit,
      final String filter,
      final OrderByEnum orderByEnum,
      final Boolean descOrAsc) {
    Query finalQuery =
        getSession().createQuery(BY_VDC_TO_PURCHASE + " " + defineOrderBy(orderByEnum, descOrAsc));
    finalQuery.setParameter("vdc_id", vdcId);
    finalQuery.setParameter(
        "filterLike", filter == null || filter.isEmpty() ? "%" : "%" + filter + "%");

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

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

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

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

    return ipList;
  }
Example #5
0
  public List<IpPoolManagement> findIpsByVdc(
      final Integer vdcId,
      Integer firstElem,
      final Integer numElem,
      final String has,
      final IpPoolManagement.OrderByEnum orderby,
      final Boolean asc) {
    // Get the query that counts the total results.
    Query finalQuery = getSession().createQuery(BY_VDC + " " + defineOrderBy(orderby, asc));
    finalQuery.setParameter("vdc_id", vdcId);
    finalQuery.setParameter("filterLike", has.isEmpty() ? "%" : "%" + has + "%");

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

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

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

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

    return ipList;
  }
 @Override
 public Role findRoleByRoleId(Integer roleId) {
   String hql = "FROM Role r WHERE r.roleId =:roleId";
   Query query = getSession().createQuery(hql);
   query.setParameter("roleId", roleId);
   return (Role) ((query.list().size() > 0) ? query.list().get(0) : null);
 }
Example #7
0
  public List<Rating> getSchoolRating(Integer schoolId) {
    String HQL =
        "SELECT ratingCategoryType.id as catid, ratingCategoryType.categoryName as name, avg(rating) as rating, count(ratingCategoryType.id) as ratingCount, COALESCE(ratingCategoryType.image,'') as image from UserRating where school.id = :schoolId GROUP BY ratingCategoryType.id";
    HibernateUtil hibernateUtil = new HibernateUtil();
    Session session = hibernateUtil.openSession();

    Query query =
        session.createQuery(HQL).setResultTransformer(Transformers.aliasToBean(Rating.class));
    query.setParameter("schoolId", schoolId);
    session.flush();
    List<Rating> schoolRatings = query.list();
    if (schoolRatings.size() <= 0) {
      String newhql =
          "SELECT id as catid, categoryName as name, 0.0 as rating, 0L as ratingCount, COALESCE(image,'') as image from RatingCategoryType";
      Session newsession = hibernateUtil.openSession();
      Query newquery =
          newsession
              .createQuery(newhql)
              .setResultTransformer(Transformers.aliasToBean(Rating.class));
      newsession.flush();
      schoolRatings = newquery.list();
    }

    return schoolRatings;
  }
  public void testSetProperties() throws Exception {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Simple simple = new Simple();
    simple.setName("Simple 1");
    s.save(simple, new Long(10));
    Query q = s.createQuery("from Simple s where s.name=:name and s.count=:count");
    q.setProperties(simple);
    assertTrue(q.list().get(0) == simple);
    // misuse of "Single" as a propertyobject, but it was the first testclass i found with a
    // collection ;)
    Single single = new Single() { // trivial hack to test properties with arrays.
          String[] getStuff() {
            return (String[]) getSeveral().toArray(new String[getSeveral().size()]);
          }
        };

    List l = new ArrayList();
    l.add("Simple 1");
    l.add("Slimeball");
    single.setSeveral(l);
    q = s.createQuery("from Simple s where s.name in (:several)");
    q.setProperties(single);
    assertTrue(q.list().get(0) == simple);

    q = s.createQuery("from Simple s where s.name in (:stuff)");
    q.setProperties(single);
    assertTrue(q.list().get(0) == simple);
    s.delete(simple);
    t.commit();
    s.close();
  }
  public void addMansion(Mansion m) {

    Session session = sf.getCurrentSession();

    session.beginTransaction();

    session.save(m);

    session.getTransaction().commit();

    Session session2 = sf.getCurrentSession();

    session2.beginTransaction();

    Query query = session2.createQuery("from Mansion");
    List<Mansion> mlist = query.list();
    for (Mansion onem : mlist) {
      System.out.println(onem.getA().size());
    }

    Query query2 = session2.createQuery("from Aristocrat");
    List<Aristocrat> alist = query2.list();
    for (Aristocrat onea : alist) {
      System.out.println("An aristocrat...");
    }

    session2.close();
  }
Example #10
0
 /**
  * QL 分页查询
  *
  * @param page
  * @param qlString
  * @param parameter
  * @return
  */
 @SuppressWarnings("unchecked")
 public <E> Page<E> find(Page<E> page, String qlString, Parameter parameter) {
   // get count
   if (!page.isDisabled() && !page.isNotCount()) {
     String countQlString = "select count(*) " + removeSelect(removeOrders(qlString));
     //	        page.setCount(Long.valueOf(createQuery(countQlString,
     // parameter).uniqueResult().toString()));
     Query query = createQuery(countQlString, parameter);
     List<Object> list = query.list();
     if (list.size() > 0) {
       page.setCount(Long.valueOf(list.get(0).toString()));
     } else {
       page.setCount(list.size());
     }
     if (page.getCount() < 1) {
       return page;
     }
   }
   // order by
   String ql = qlString;
   if (StringUtils.isNotBlank(page.getOrderBy())) {
     ql += " order by " + page.getOrderBy();
   }
   Query query = createQuery(ql, parameter);
   // set page
   if (!page.isDisabled()) {
     query.setFirstResult(page.getFirstResult());
     query.setMaxResults(page.getMaxResults());
   }
   page.setList(query.list());
   return page;
 }
  @Override
  public PageBean findAppPictures(String currentPage, String factoryid) {
    // TODO Auto-generated method stub

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

    Query query =
        getSession()
            .createQuery(
                "from App_picture  p where    p.factory.id='" + factoryid + "' "); // 带条件的查询语句
    int count = query.list().size();
    query.setFirstResult(firdata);
    query.setMaxResults(10);
    List<App_picture> list = query.list();
    while (list.size() == 0 && curpage > 1) {
      curpage -= 1;
      firdata = (curpage - 1) * 10;
      query =
          getSession()
              .createQuery(
                  "from App_picture p where    p.factory.id='" + factoryid + "' "); // 带条件的查询语句
      count = query.list().size();
      query.setFirstResult(firdata);
      query.setMaxResults(10);
      list = query.list();
      if (list.size() > 0) break;
    }
    PageBean pagebean = new PageBean(curpage, 10, count, list);
    return pagebean;
  }
Example #12
0
  /**
   * Return all the IPs from a VLAN filtered by a string and saying how many elements do you want
   * and the first element to retrieve
   *
   * @param network {@link Network} network entity that stores all the VLANs
   * @param vlanId identifier of the VLAN to search into.
   * @param has to filter the search
   * @param firstElem firstelement to retrieve.
   * @param numeElem to retrieve.
   * @return all the {@link IpPoolManagement} ips.
   */
  public List<IpPoolManagement> findIpsByNetwork(
      final Network network,
      final Integer vlanId,
      final String has,
      Integer firstElem,
      final Integer numElem) {
    Query finalQuery = getSession().createQuery(BY_NETWORK);
    finalQuery.setParameter("net_id", network.getId());
    finalQuery.setParameter("vlan_id", vlanId);
    finalQuery.setParameter("filterLike", has == null || has.isEmpty() ? "%" : "%" + has + "%");

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

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

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

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

    return ipList;
  }
  @Override
  public String execute() throws Exception {
    // TODO Auto-generated method stub
    List<UrpTeacher> teacherData;
    List<UrpCollege> collegeData;
    this.result = new ArrayList<HashMap<String, String>>();

    Session session = HibernateSessionFactory.getSession();
    Transaction trans = session.beginTransaction();

    Query teacherQuery = session.createQuery("from UrpTeacher");
    Query collegeQuery = session.createQuery("from UrpCollege");
    teacherData = teacherQuery.list();
    collegeData = collegeQuery.list();
    trans.commit();

    for (UrpCollege college : collegeData) {
      HashMap<String, String> c = new HashMap<String, String>();
      c.put("id", college.getCollegeNo());
      c.put("text", college.getCollegeNo() + "-" + college.getName());
      result.add(c);
    }

    for (UrpTeacher teacher : teacherData) {
      HashMap<String, String> t = new HashMap<String, String>();
      t.put("id", teacher.getTeacherNo());
      t.put("text", teacher.getTeacherNo() + "-" + teacher.getTeacherName());
      t.put("pid", teacher.getCollege().getCollegeNo());
      result.add(t);
    }
    HibernateSessionFactory.closeSession();
    return SUCCESS;
  }
  @Test
  public void testSpecificQueryRegionEviction() {
    int entityCount = 10;
    insertDummyEntities(entityCount, 0);
    // miss 1 query list entities
    Session session = sf.openSession();
    Transaction txn = session.beginTransaction();
    Query query = session.createQuery("from " + DummyEntity.class.getName());
    query.setCacheable(true).setCacheRegion("newregionname");
    query.list();
    txn.commit();
    session.close();
    // query is cached

    // query is invalidated
    sf.getCache().evictQueryRegion("newregionname");

    // miss 1 query
    session = sf.openSession();
    txn = session.beginTransaction();
    query = session.createQuery("from " + DummyEntity.class.getName());
    query.setCacheable(true);
    query.list();
    txn.commit();
    session.close();

    assertEquals(0, sf.getStatistics().getQueryCacheHitCount());
    assertEquals(2, sf.getStatistics().getQueryCacheMissCount());
  }
Example #15
0
  public static void main(String[] args) {
    Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
    SessionFactory factory = cfg.buildSessionFactory();

    Session session1 = factory.openSession();
    Employee emp1 = (Employee) session1.load(Employee.class, 1);
    System.out.println(emp1.getId() + " " + emp1.getName() + " " + emp1.getDesignation());
    session1.close();

    Session session2 = factory.openSession();
    Employee emp2 = (Employee) session2.load(Employee.class, 1);
    System.out.println(emp2.getId() + " " + emp2.getName() + " " + emp2.getDesignation());
    session2.close();

    Session sess = factory.openSession();
    Query query = sess.getNamedQuery("employee.select").setInteger("id", 1);

    List<Employee> emp3 = query.list();

    for (Employee emp : emp3) {

      System.out.println(emp.getId() + " " + emp.getName() + " " + emp.getDesignation());
    }

    Session sess1 = factory.openSession();
    Query query1 = sess.getNamedQuery("employee.select").setInteger("id", 1);

    List<Employee> emp4 = query.list();

    for (Employee emp : emp4) {

      System.out.println(emp.getId() + " " + emp.getName() + " " + emp.getDesignation());
    }
  }
Example #16
0
 @SuppressWarnings("unchecked")
 public Page<T> findPage(String qlString, List<Object> parameter, Pageable pageable) {
   if (pageable == null) pageable = new Pageable();
   StringBuilder stringBuilder = new StringBuilder(qlString);
   addFilter(stringBuilder, pageable, parameter);
   addOrders(stringBuilder, pageable, parameter);
   qlString = stringBuilder.toString();
   if (qlString.indexOf("order by") == -1) {
     if (OrderEntity.class.isAssignableFrom(this.entityClass)) {
       qlString += "order by order ASC";
     } else {
       qlString += "order by createDate DESC";
     }
   }
   long count = count(stringBuilder, null, parameter);
   int i = (int) Math.ceil((double) count / pageable.getPageSize());
   if (i < pageable.getPageNumber()) {
     pageable.setPageNumber(i);
   }
   System.out.println("query=" + qlString);
   for (Object object : parameter) {
     System.out.println("object=" + object);
   }
   Query query = createQuery(qlString, parameter.toArray());
   query.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize());
   query.setMaxResults(pageable.getPageSize());
   List<Object> list = query.list();
   if (list.size() > 0) {
     return new Page<T>(query.list(), count, pageable);
   }
   List<T> listTemp = new ArrayList<T>();
   return new Page<T>(listTemp, count, pageable);
 }
  @SuppressWarnings("unchecked")
  @Override
  public Page<T> findByPage(Page<T> page, String hql, Object... values) {
    Query queryObject = createQuery(hql, values);

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

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

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

        List<T> result = (List<T>) queryObject.list();
        page.setResult(result);
      }
    } else {
      page.setTotal(0);
    }
    return page;
  }
 @Override
 public Job getJob(String jobUid) {
   Query query =
       getSession()
           .createQuery("FROM Job job  WHERE job.jobUid=:jobUid")
           .setParameter("jobUid", jobUid);
   return (Job) (query.list().size() > 0 ? query.list().get(0) : null);
 }
Example #19
0
 public void updateSchoolFinalRating(SchoolRating schoolRating) {
   String HQL =
       "SELECT COUNT(id) as userCount, SUM(rating) as totalRating from UserRating where school.id = :schoolId";
   HibernateUtil hibernateUtil = new HibernateUtil();
   Session session = hibernateUtil.openSession();
   Query query =
       session.createQuery(HQL).setResultTransformer(Transformers.aliasToBean(TotalRating.class));
   query.setParameter("schoolId", schoolRating.getSchool().getId());
   List<TotalRating> totalRatings = query.list();
   session.flush();
   System.out.println(
       "total rating:"
           + totalRatings.get(0).getTotalRating()
           + " count"
           + totalRatings.get(0).getUserCount());
   if (totalRatings.size() > 0) {
     String sql = "from SchoolRating where school.id =" + schoolRating.getSchool().getId();
     Session sqlseSession = hibernateUtil.openSession();
     Query sqlQuery = sqlseSession.createQuery(sql);
     boolean newRating = sqlQuery.list().size() > 0 ? true : false;
     sqlseSession.flush();
     /*String newhql = "SELECT id from RatingCategoryType";
     Session newsession1 = hibernateUtil.openSession();
     Query newquery1 = newsession1.createQuery(newhql);
     int catSize = newquery1.list().size() > 0 ?newquery1.list().size():0;
     newsession1.flush();*/
     if (newRating) {
       long calculated_rating =
           Math.round(
               totalRatings.get(0).getTotalRating() / totalRatings.get(0).getUserCount() * 100);
       float final_rating = (float) calculated_rating / 100;
       System.out.println("Rating:" + final_rating);
       String updatehql =
           "UPDATE SchoolRating set rating="
               + final_rating
               + " where school.id="
               + schoolRating.getSchool().getId();
       Session newsession = hibernateUtil.openSession();
       newsession.beginTransaction();
       Query newquery = newsession.createQuery(updatehql);
       newquery.executeUpdate();
       newsession.getTransaction().commit();
       newsession.flush();
     } else {
       long calculated_rating =
           Math.round(
               totalRatings.get(0).getTotalRating() / totalRatings.get(0).getUserCount() * 100);
       float final_rating = (float) calculated_rating / 100;
       System.out.println("Rating:" + final_rating);
       schoolRating.setRating(final_rating);
       Session newsession = hibernateUtil.openSession();
       newsession.beginTransaction();
       newsession.save(schoolRating);
       newsession.getTransaction().commit();
       newsession.flush();
     }
   }
 }
 @Override
 public School getSchoolById(Integer id) {
   Query query = getSession().createQuery("from School where id = ? ");
   query.setInteger(0, id);
   if (query.list() == null || query.list().size() == 0) {
     return null;
   }
   return (School) query.list().get(0);
 }
 @Override
 public MenuRoleAssoc findMenuRoleAssocEntryByRoleIdAndMenuUid(Integer roleId, String menuUid) {
   String hql =
       "FROM MenuRoleAssoc MRA WHERE MRA.role.roleId = :roleId and MRA.menu.menuUid = :menuUid";
   Query query = getSession().createQuery(hql);
   query.setParameter("roleId", roleId);
   query.setParameter("menuUid", menuUid);
   return (MenuRoleAssoc) (query.list().size() > 0 ? query.list().get(0) : null);
 }
 @Override
 public School getSchoolByLoginName(String name) {
   Query query = getSession().createQuery("from School where name = ? ");
   query.setString(0, name);
   if (query.list() == null || query.list().size() == 0) {
     return null;
   }
   return (School) query.list().get(0);
 }
Example #23
0
  // 根据toid查找消息
  public List<Message> findlaterMessage(int toid) {

    List<Message> list = new ArrayList<Message>();

    //		List<Message> listspo=hibernateTemplate.find("from Message m where m.toid=? and type=4 group
    // by m.invid order by m.time desc",toid);
    //		List<Message> listuser=hibernateTemplate.find("from Message m where m.toid=? and type=0
    // group by m.fromid order by m.time desc",toid);
    //		List<Message> listinv=hibernateTemplate.find("from Message m where m.toid=? and type>4 group
    // by m.invid order by m.time desc",toid);
    Session session = hibernateTemplate.getSessionFactory().openSession();

    Query query =
        session.createQuery(
            "from Message m where m.toid=? and type=4 group by m.invid order by m.time desc");
    query.setInteger(0, toid);
    //		session.close();
    @SuppressWarnings("unchecked")
    List<Message> listspo = query.list();
    Query query2 =
        session.createQuery(
            "from Message m where m.toid=? and type=0 group by m.fromid order by m.time desc");
    query2.setInteger(0, toid);
    @SuppressWarnings("unchecked")
    List<Message> listuser = query2.list();
    Query query3 =
        session.createQuery(
            "from Message m where m.toid=? and type>4 group by m.invid order by m.time desc");
    query3.setInteger(0, toid);
    @SuppressWarnings("unchecked")
    List<Message> listinv = query3.list();
    session.close();

    hibernateTemplate.getSessionFactory().close();

    //		List<Message> listspo= hibernateTemplate
    //				.find("  from Message m where m.toid=? and type=4 group by m.invid order by m.time desc",
    //						toid);
    //		List<Message> listuser = hibernateTemplate
    //				.find("from Message m where m.toid=? and type<4 group by m.fromid order by m.time desc",
    //						toid);
    //
    //		List<Message> listinv = hibernateTemplate
    //				.find("from Message m where m.toid=? and type>4 group by m.invid order by m.time desc",
    //						toid);
    if (listinv.size() != 0) {
      list.addAll(listinv);
    }
    if (listspo.size() != 0) {
      list.addAll(listspo);
    }
    if (listuser.size() != 0) {
      list.addAll(listuser);
    }

    return list;
  }
 /**
  * find entity-s of database by hql, through setQueryParams(...)
  * --------------------------------------------------------
  */
 @SuppressWarnings("unchecked")
 public List<T> findByPage(String hql, List<Object> values) {
   if (hql == null) {
     return new ArrayList<T>();
   }
   Query query = createQuery(hql);
   setQueryParams(query, values);
   if (query.list() != null) return query.list();
   else return null;
 }
Example #25
0
  public List<OsunitHasS> getOsunitHasSBySid(long sid) {
    Query qurey = this.getSession().createQuery("from OsunitHasS where sid=?");
    qurey.setParameter(0, sid);
    if (qurey.list().size() > 0) {
      return qurey.list();

    } else {
      return null;
    }
  }
Example #26
0
 @Override
 public List findInCompleteOrders() {
   Query query =
       sessionFactory.getCurrentSession().createQuery("from Order o where o.isComplite=false");
   List<Order> orderList = query.list();
   for (Order or : orderList) {
     System.out.println(or);
   }
   return query.list();
 }
  @Test
  public void indexingTest() {
    POI poi = new POI(1, "Test", 24.0d, 32.0d, "");

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    FullTextSession fullTextSession = Search.getFullTextSession(session);

    try {
      session.save(poi);
      fullTextSession.index(poi);
      fullTextSession.flushToIndexes();
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail("Exception thrown when index point");
    }

    try {
      Point center = Point.fromDegrees(24, 31.5); // 50.79 km fromBoundingCircle 24.32

      org.apache.lucene.search.Query luceneQuery =
          SpatialQueryBuilder.buildGridQuery(center, 50, "location");
      org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery(luceneQuery, POI.class);
      List results = hibQuery.list();
      Assert.assertEquals(1, results.size());

      org.apache.lucene.search.Query luceneQuery2 =
          SpatialQueryBuilder.buildGridQuery(center, 1, "location");
      org.hibernate.Query hibQuery2 = fullTextSession.createFullTextQuery(luceneQuery2, POI.class);
      List results2 = hibQuery2.list();
      Assert.assertEquals(0, results2.size());

      org.apache.lucene.search.Query luceneQuery3 =
          SpatialQueryBuilder.buildDistanceQuery(center, 50, "location");
      org.hibernate.Query hibQuery3 = fullTextSession.createFullTextQuery(luceneQuery3, POI.class);
      List results3 = hibQuery3.list();
      Assert.assertEquals(0, results3.size());

      org.apache.lucene.search.Query luceneQuery4 =
          SpatialQueryBuilder.buildSpatialQuery(center, 50, "location");
      org.hibernate.Query hibQuery4 = fullTextSession.createFullTextQuery(luceneQuery4, POI.class);
      List results4 = hibQuery4.list();
      Assert.assertEquals(0, results4.size());

      org.apache.lucene.search.Query luceneQuery5 =
          SpatialQueryBuilder.buildSpatialQuery(center, 51, "location");
      org.hibernate.Query hibQuery5 = fullTextSession.createFullTextQuery(luceneQuery5, POI.class);
      List results5 = hibQuery5.list();
      Assert.assertEquals(1, results5.size());

    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail("Exception thrown when querying point");
    }
  }
  public void testStringVariableQuery() {
    ProcessDefinition processDefinition =
        ProcessDefinition.parseXmlString(
            "<process-definition name='variables'>"
                + "  <start-state name='start'/>"
                + "</process-definition>");
    deployProcessDefinition(processDefinition);

    ProcessInstance one = jbpmContext.newProcessInstanceForUpdate("variables");
    one.getContextInstance().setVariable("category", "overpaid");
    one.getContextInstance().setVariable("duedate", "tomorrow");

    ProcessInstance two = jbpmContext.newProcessInstanceForUpdate("variables");
    two.getContextInstance().setVariable("category", "overpaid");
    two.getContextInstance().setVariable("duedate", "yesterday");

    ProcessInstance three = jbpmContext.newProcessInstanceForUpdate("variables");
    three.getContextInstance().setVariable("category", "underpaid");
    three.getContextInstance().setVariable("duedate", "today");

    newTransaction();

    Set expectedPids = new HashSet();
    expectedPids.add(new Long(one.getId()));
    expectedPids.add(new Long(two.getId()));

    Query query =
        session.createQuery(
            "select pi.id "
                + "from org.jbpm.context.exe.variableinstance.StringInstance si "
                + "join si.processInstance pi "
                + "where si.name = 'category'"
                + "  and si.value like 'overpaid'");
    Set retrievedPids = new HashSet(query.list());

    assertEquals(expectedPids, retrievedPids);

    newTransaction();

    expectedPids.clear();
    expectedPids.add(new Long(three.getId()));

    query =
        session.createQuery(
            "select pi.id "
                + "from org.jbpm.context.exe.variableinstance.StringInstance si "
                + "join si.processInstance pi "
                + "where si.name = 'category'"
                + "  and si.value like 'underpaid'");
    retrievedPids.clear();
    retrievedPids.addAll(query.list());

    assertEquals(expectedPids, retrievedPids);
  }
Example #29
0
 /**
  * Method to load cases in state "Saved" and "With result". These are the cases which hasn't been
  * closed, so the result of this can be changed.
  *
  * @param session
  * @return
  */
 public List<Labcase> listPendingCases(Session session) {
   Query hql =
       session.createQuery("from Labcase where state in (:status1, :status2) order by code");
   hql.setParameter("status1", Labcase.SAVED);
   hql.setParameter("status2", Labcase.WITHRESULT);
   List<Labcase> pendingCases = hql.list();
   for (Labcase labcase : pendingCases) {
     Hibernate.initialize(labcase.getEnterpriseSender());
   }
   return hql.list();
 }
Example #30
0
  /**
   * Get user by username
   *
   * @param username
   * @return
   */
  public User getUser(String username) {
    hql = "from User u where u.username = :username";
    query = getCurrentSession().createQuery(hql);
    query.setParameter("username", username);

    if (query.list().isEmpty()) {
      return null;
    } else {
      return (User) query.list().get(0);
    }
  }