Example #1
1
  public static Topic createFromDB(int topicID) {
    Topic topic = null;
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select t, count(p.postID) "
                  + "  from Topic as t, Post as p "
                  + " where t.topicID = p.topicID "
                  + "   and t.topicID = :topicid "
                  + " group by t.topicID");
      q.setInteger("topicid", topicID);

      for (Iterator<Object[]> it = q.iterate(); it.hasNext(); ) {
        Object[] el = it.next();
        topic = (Topic) el[0];
        Long replies = (Long) el[1];
        topic.setReplies(replies == null ? 0 : replies.intValue());
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return topic;
  }
  public Long countPedidosRealizadosByUsuario(Usuario usuario) {
    final Query query =
        createQuery("select count(p) from Pedido p " + "where p.usuario.id = :idusuario");
    query.setParameter("idusuario", usuario.getId());

    return ((Long) query.iterate().next());
  }
Example #3
0
 public Iterator iterate(String queryString, Object... values) {
   Query query = getSession().createQuery(queryString);
   for (int position = 0; position < values.length; position++) {
     query.setParameter(position, values[position]);
   }
   return query.iterate();
 }
  @Override
  public int countProgramInstances(ProgramInstanceQueryParams params) {
    String hql = buildProgramInstanceHql(params);
    Query query = getQuery(hql);

    return ((Number) query.iterate().next()).intValue();
  }
  public static void main(String[] args) {
    Session session = null;

    try {

      SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
      session = sessionFactory.openSession();

      Contact contact;

      String SQL_QUERY = "select c.id, c.firstName from Contact  c where c.id >= 3";

      Query query = session.createQuery(SQL_QUERY);
      Iterator it = query.iterate();
      while (it.hasNext()) {
        Object[] row = (Object[]) it.next();
        System.out.println("------------------------------------------------------");
        System.out.println("ID                : " + row[0]);
        System.out.println("First Name  : " + row[1]);
      }

      System.out.println("Done");
    } catch (Exception e) {
      // tx.rollback();
      System.out.println(e.getMessage());
    } finally {

      // session.flush();
      session.close();
    }
  }
  public void initParam() {
    if (logger.isInfoEnabled()) {
      logger.info("**************卡库不平分析线程初始化**************"); // $NON-NLS-1$
    }
    try {
      Session session = HibernateSessionFactory.currentSession();
      Query queryTime =
          session.createQuery(
              "from MapAnalysisPoint as point where point.analysisname=:analysisName");
      queryTime.setString("analysisName", "UNBALANCE_ERROR");
      Iterator iterTime = queryTime.iterate();
      if (iterTime.hasNext()) {
        MapAnalysisPoint mapAnalysisPoint = (MapAnalysisPoint) iterTime.next();
        this.startTime = mapAnalysisPoint.getAnalysispoint();
      }

      if (!"20050101000000".equals(this.startTime)) {
        this.endTime = DateUtil.getNewTime(startTime, doubleCycle);
      } else {
        this.endTime = DateUtil.getNow();
        this.startTime = DateUtil.getNewTime(this.endTime, -doubleCycle);
      }

    } catch (HibernateException e) {
      logger.error("卡库不平分析线程初始化失败!", e); // $NON-NLS-1$
    } finally {
      HibernateSessionFactory.closeSession();
    }
    if (logger.isInfoEnabled()) {
      logger.info("**************卡库不平分析线程初始化成功**************"); // $NON-NLS-1$
    }
  }
  /**
   * Runs the query by calling <code>org.hibernate.Query.iterate()</code>.
   *
   * @return query iterator
   */
  public Iterator<?> iterate() {
    setMaxCount();

    setQueryRunning(true);
    try {
      return query.iterate();
    } finally {
      setQueryRunning(false);
    }
  }
Example #8
0
  public Iterator getData() throws Exception {
    // TODO Auto-generated method stub
    System.out.println("In spring class getData()");
    Session ses = factory.openSession();
    Query query = ses.createQuery("FROM DBUser");
    Iterator i1 = query.iterate();
    ses.close();

    return i1;
  }
  public Long countPedidosConcluidosByUsuario(Usuario usuario) {
    final Query query =
        createQuery(
            "select count(p) from Pedido p "
                + "where p.usuario.id = :idusuario and statusPedido = :status");
    query.setParameter("idusuario", usuario.getId());
    query.setParameter("status", EStatusPedido.CONCLUIDO);

    return ((Long) query.iterate().next());
  }
Example #10
0
  /**
   * 通过Finder获得记录总数
   *
   * @param finder 条件组装器
   * @return 记录数
   */
  public int countQueryResult(Finder finder) {
    String hql = finder.getRowCountHql();
    Query query = getSession().createQuery(hql);
    finder.setParamsToQuery(query);

    if (finder.isCacheable()) {
      query.setCacheable(true);
    }

    return ((Number) query.iterate().next()).intValue();
  }
Example #11
0
 public int countByChannelId(int channelId) {
   String hql =
       "select count(*) from Content bean"
           + " join bean.channel channel,Channel parent"
           + " where channel.lft between parent.lft and parent.rgt"
           + " and channel.site.id=parent.site.id"
           + " and parent.id=:parentId";
   Query query = getSession().createQuery(hql);
   query.setParameter("parentId", channelId);
   return ((Number) (query.iterate().next())).intValue();
 }
Example #12
0
 /** 查询全部 */
 public void iterator() {
   SessionFactory sessionFactory = ExampleHibernateUtil.getSessionFactory();
   Session session = sessionFactory.openSession();
   String hql = "from Object";
   Query query = session.createQuery(hql);
   Iterator<Object> it = query.iterate();
   while (it.hasNext()) {
     Object obj = it.next();
     System.out.println(obj);
   }
   session.close();
 }
Example #13
0
 // 需要为<class name="Emp" lazy="false">...</class>添加lazy="false",测试才通过
 @Test
 public void test_iterator() {
   SessionFactory sessionFactory = SessionFactoryUtils.getSessionFactory();
   Session session = sessionFactory.openSession();
   String hql = "from Emp";
   Query query = session.createQuery(hql);
   Iterator<Emp> it = query.iterate();
   while (it.hasNext()) {
     Emp emp = it.next();
     System.out.println(emp);
   }
   session.close();
 }
 public List<Kontakt> getAll() {
   List<Kontakt> items = new ArrayList<>();
   createSession();
   Transaction t = (Transaction) getSession().beginTransaction();
   Query q = getSession().createQuery("SELECT k FROM Kontakt k");
   Iterator<Kontakt> result = q.iterate();
   while (result.hasNext()) {
     items.add(result.next());
   }
   t.commit();
   closeSession();
   return items;
 }
Example #15
0
 public static java.util.Iterator iterateInfratypeByQuery(
     Session session, String condition, String orderBy) throws PersistentException {
   StringBuffer sb = new StringBuffer("From Infratype as Infratype");
   if (condition != null) sb.append(" Where ").append(condition);
   if (orderBy != null) sb.append(" Order By ").append(orderBy);
   try {
     Query query = session.createQuery(sb.toString());
     return query.iterate();
   } catch (Exception e) {
     Debug.println(e);
     throw new PersistentException(e);
   }
 }
  /** @author alizadeh */
  @Override
  public QueryResult<AdjustmentEstimateDetailsDto> getCamp5YearEstimateAmmunitions(
      int estimateId, int tadilPercent, int priceShowType, SearchOption searchOption) {
    HashMap<String, Object> params = new HashMap<String, Object>();
    String hql =
        " select e.id as id,e.goodType.title as  ammoTitle,e.quantity as quantity,e.fee as fi,"
            + " cast(((e.quantity*e.fee)/:priceShowType) as long) as rialCost ,"
            + " round( e.quantity-((e.quantity/100)*:tadilPercent)) as quantityAfterAdjustment,"
            + " cast((round((e.quantity-((e.quantity/100)*:tadilPercent))*e.fee)/:priceShowType) as long)as  rialCostAfterAdjustment "
            + " from "
            + domainClass.getName()
            + " e where  e.camp5YearEstimate.id =:estimateId ";
    params.put("estimateId", estimateId);
    params.put("tadilPercent", tadilPercent);
    params.put("priceShowType", priceShowType);
    List<AdjustmentEstimateDetailsDto> list =
        getAll(hql, params, searchOption, AdjustmentEstimateDetailsDto.class);
    int count = 0;
    if (!list.isEmpty()) {
      Session session = getSession();
      String QueryCount =
          "select count(*) from  "
              + domainClass.getName()
              + " e where  e.camp5YearEstimate.id =:estimateId ";
      String QuerySum =
          " select cast((sum(e.quantity*e.fee)/:priceShowType) as long )as sumOfRialCost,"
              + " (cast((sum(round((e.quantity-((e.quantity/100)*:tadilPercent))*e.fee))/:priceShowType)as long)) as sumOfRialCostAfterAdjustment "
              + " from "
              + domainClass.getName()
              + " e where  e.camp5YearEstimate.id =:estimateId ";

      StringBuffer jqlCount = new StringBuffer(QueryCount);
      StringBuffer jqlSum = new StringBuffer(QuerySum);
      Query countQuery = session.createQuery(jqlCount.toString());
      Query querySum = session.createQuery(jqlSum.toString());
      countQuery.setParameter("estimateId", estimateId);
      querySum.setParameter("estimateId", estimateId);
      querySum.setLong("tadilPercent", tadilPercent);
      querySum.setLong("priceShowType", priceShowType);
      Iterator iterator = querySum.iterate();
      if (iterator.hasNext() && list.size() > 0) {
        Object[] row = (Object[]) iterator.next();
        list.get(0).setSumOfRialCost(Long.parseLong(row[0].toString()));
        list.get(0).setSumOfRialCostAfterAdjustment(Long.parseLong(row[1].toString()));
      }
      Integer res = ((Long) countQuery.uniqueResult()).intValue();
      if (res != null) count = res;
    }
    return new QueryResult<AdjustmentEstimateDetailsDto>(
        searchOption.getPageNumber(), count, searchOption.getPageSize(), list);
  }
Example #17
0
 public static java.util.Iterator iterateBRADYSETByQuery(
     PersistentSession session, String condition, String orderBy) {
   StringBuffer sb = new StringBuffer("From tr.com.srdc.icardea.hibernate.BRADYSET as BRADYSET");
   if (condition != null) sb.append(" Where ").append(condition);
   if (orderBy != null) sb.append(" Order By ").append(orderBy);
   try {
     Query query = session.createQuery(sb.toString());
     return query.iterate();
   } catch (Exception e) {
     _logger.error(
         "iterateBRADYSETByQuery(PersistentSession session, String condition, String orderBy)", e);
     return null;
   }
 }
Example #18
0
 /**
  * 获取单位单位下所有巡检人员的计划模板
  *
  * @param deptid
  * @return
  */
 public List getPatrolStencilList(String deptid) {
   /* 取得所有巡检员信息*/
   String hql = "from PatrolMan  where parentid=:deptid and state is  NULL"; //
   List patrollist = new ArrayList();
   Session session = bdao.getSession();
   Transaction tx = null;
   try {
     PatrolManBean pmb = null;
     tx = session.beginTransaction();
     Query query = session.createQuery(hql);
     query.setParameter("deptid", deptid);
     // query.setParameter("state", "1");
     Iterator it = query.iterate();
     while (it.hasNext()) {
       pmb = new PatrolManBean();
       PatrolMan pm = (PatrolMan) it.next();
       logger.info("巡检组名" + pm.getPatrolName());
       BeanUtil.objectCopy(pm, pmb);
       String hql_stencil = "from  StencilTask where patrolid=:patrolid";
       Query query_st = session.createQuery(hql_stencil);
       query_st.setParameter("patrolid", pm.getPatrolID());
       Iterator it_st = query_st.iterate();
       while (it_st.hasNext()) {
         StencilTaskBean stencil = new StencilTaskBean();
         StencilTask st = (StencilTask) it_st.next();
         BeanUtil.objectCopy(st, stencil);
         pmb.getTemp().add(stencil);
       }
       patrollist.add(pmb);
     }
     return patrollist;
   } catch (Exception e) {
     logger.error(e);
     e.printStackTrace();
     return null;
   }
 }
 /**
  * @param session
  * @param condition
  * @param orderBy
  * @return
  * @throws PersistentException
  */
 public static java.util.Iterator iterateCommentTaskByQuery(
     PersistentSession session, String condition, String orderBy) throws PersistentException {
   StringBuffer sb = new StringBuffer("From de.fhb.jproject.data.CommentTask as CommentTask");
   if (condition != null) sb.append(" Where ").append(condition);
   if (orderBy != null) sb.append(" Order By ").append(orderBy);
   try {
     Query query = session.createQuery(sb.toString());
     return query.iterate();
   } catch (Exception e) {
     _logger.error(
         "iterateCommentTaskByQuery(PersistentSession session, String condition, String orderBy)",
         e);
     throw new PersistentException(e);
   }
 }
 @Test
 public void testColumnMapping() throws Exception {
   Session session = sessionFactory.openSession();
   try {
     Map metadata = sessionFactory.getAllClassMetadata();
     for (Object o : metadata.values()) {
       EntityPersister persister = (EntityPersister) o;
       String className = persister.getEntityName();
       log.debug("Trying select * from: " + className);
       Query q = session.createQuery("from " + className + " c");
       q.iterate();
       log.debug("ok: " + className);
     }
   } finally {
     session.close();
   }
 }
Example #21
0
 public void deleteAssemblyRoom(String ids[]) throws HibernateException {
   Session s = getSession();
   StringBuffer sqlStr = new StringBuffer();
   sqlStr.append(" from TAssemblyRoom where roomId in ('" + ids[0] + "' ");
   for (int i = 1, l = ids.length; i < l; i++) {
     sqlStr.append(", '" + ids[i] + "' ");
   }
   sqlStr.append(")");
   try {
     Query q = s.createQuery(sqlStr.toString());
     Iterator iter = q.iterate();
     while (iter.hasNext()) {
       s.delete(iter.next());
     }
   } catch (HibernateException ex) {
     errlog.error(ex);
     throw ex;
   }
 }
Example #22
0
 public static java.util.Iterator iterateMedicationByQuery(
     PersistentSession session,
     String condition,
     String orderBy,
     org.hibernate.LockMode lockMode) {
   StringBuffer sb =
       new StringBuffer("From tr.com.srdc.icardea.hibernate.Medication as Medication");
   if (condition != null) sb.append(" Where ").append(condition);
   if (orderBy != null) sb.append(" Order By ").append(orderBy);
   try {
     Query query = session.createQuery(sb.toString());
     query.setLockMode("this", lockMode);
     return query.iterate();
   } catch (Exception e) {
     _logger.error(
         "iterateMedicationByQuery(PersistentSession session, String condition, String orderBy)",
         e);
     return null;
   }
 }
Example #23
0
  public int findNumberOfPlayersInLeague(final League league) {

    //		  return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
    //			   public Object doInHibernate(Session session) throws HibernateException, SQLException {
    //				   Query query = session.createQuery("select count(playerleague.player) from PlayerLeague
    // playerleague where playerleague.league.id=?").setLong(0, league.getId());
    ////					"select count(playerleague.player) from PlayerLeague playerleague where
    // playerleague.league.id=?").setLong(0, league.getId());
    //					return Integer.parseInt(""+query.iterate().next());
    //				   }
    //				  });

    Query query =
        getQuery(
            "select count(playerleague.player) from PlayerLeague playerleague where playerleague.league.id=?");
    query.setParameter(0, league.getId());

    int num = Integer.parseInt("" + query.iterate().next());
    return num;
  }
Example #24
0
  public static List<Topic> getTopics(int location, int offset) {

    List<Topic> topics = new Vector<Topic>();

    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select u, t, count(p.postID) "
                  + "  from Topic as t, User as u, Post as p "
                  + " where t.starter = u.id "
                  + "   and t.location = :location "
                  + "   and p.topicID = t.topicID "
                  + " group by t.topicID "
                  + " order by t.sticky desc, t.lastedit desc");
      q.setMaxResults(Topic.MAXTOPICS);
      if (offset > 0) {
        q.setFirstResult(offset);
      }
      q.setInteger("location", location);

      for (Iterator<Object[]> it = q.iterate(); it.hasNext(); ) {
        Object[] el = it.next();
        User u = (User) el[0];
        Topic topic = (Topic) el[1];
        Long replies = (Long) el[2];
        topic.setUser(u);
        topic.setReplies(replies == null ? 0 : replies.intValue());
        topics.add(topic);
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return topics;
  }
  /**
   * Handles the HTTP <code>GET</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    Session session;
    try (PrintWriter out = response.getWriter()) {
      /* TODO output your page here. You may use following sample code. */
      out.println("<!DOCTYPE html>");
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet Viewlearner</title>");
      out.println("</head>");
      out.println("<body>");
      SessionFactory sessionfactory =
          new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
      session = sessionfactory.openSession();
      session.beginTransaction();
      String hgl = "from grouppojo groups";
      org.hibernate.Query query = session.createQuery(hgl);
      // query.setParameter(hgl, out);
      System.out.println("Reading values");
      for (Iterator it = query.iterate(); it.hasNext(); ) {
        grouppojo model = (grouppojo) it.next();

        out.println("Reading the location table");
        out.println("<h2>" + model.getGroupid() + "</h2>");
        out.println("<h2>" + model.getGname() + "</h2>");
        out.println("<h2>" + model.getStart() + "</h2>");
        out.println("</br>");
      }
      session.getTransaction().commit();
      System.out.println("Done!");
      out.println("<h1>Servlet Viewlearner at " + request.getContextPath() + "</h1>");
      out.println("</body>");
      out.println("</html>");
    }
  }
  @FXML
  private void giris(ActionEvent event) throws IOException {
    Boolean durum = false;

    try {
      String sAdminAdi = kuladi.getText();
      String sAdminSifre = sifreleme(sifre.getText());

      if (sAdminAdi.equals("")) {

        Alert alert =
            new Alert(Alert.AlertType.WARNING, "Lütfen Kullanıcı Adını Giriniz.", ButtonType.OK);
        alert.setHeaderText(null);
        alert.setTitle("Uyarı");
        alert.showAndWait();
        kuladi.requestFocus();
        sifre.setText("");

        durum = true;

      } else if (sifre.getText().equals("")) {

        Alert alert = new Alert(Alert.AlertType.WARNING, "Lütfen Şifreyi Giriniz.", ButtonType.OK);
        alert.setHeaderText(null);
        alert.setTitle("Uyarı");
        alert.showAndWait();
        sifre.requestFocus();
        durum = true;

      } else {

        SessionFactory sf = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
        Session sess = sf.openSession();
        Transaction ts = sess.beginTransaction();

        Query qee = sess.createQuery("from SuperAdmin");
        Iterator ite = qee.iterate();

        while (ite.hasNext()) {

          SuperAdmin obj = (SuperAdmin) ite.next();
          String kuladi = obj.getKulAdi();
          String sifre = obj.getSifre();

          if (sAdminAdi.equals(kuladi) & sAdminSifre.equals(sifre)) {

            Integer sID = obj.getSuperID();
            //                label.setText(sID.toString());

            Parent root = null;
            Stage stage = new Stage();
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("yonlendir.fxml"));
            root = fxmlLoader.load();
            yonlendirController cont = fxmlLoader.getController();
            cont.getRefCode(sID);
            stage.setScene(new Scene(root));
            stage.show();
            durum = true;
          }
        }

        if (durum == false) {

          Alert alert =
              new Alert(Alert.AlertType.WARNING, "Hatalı Kullanıcı Adı veya Şifre", ButtonType.OK);
          alert.setHeaderText(null);
          alert.setTitle("Uyarı");
          alert.showAndWait();
          kuladi.setText("");
          sifre.setText("");
          kuladi.requestFocus();
        }

        ts.commit();
        sess.close();
      }
    } catch (HibernateException he) {
      System.out.println(he);
    }
  }
Example #27
0
  /** Execute the task */
  public void execute() throws BuildException {
    try {
      Configuration cfg = getConfiguration();
      SessionFactory sessionFactory = cfg.buildSessionFactory();

      // initialization begins here

      /* create administrator user */
      Session session = null;
      try {
        session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();

        // load predefined categories
        Query query = session.createQuery("from TermCategory where name=:name");
        query.setString("name", "Developer");
        TermCategory categoryDeveloper = (TermCategory) query.iterate().next();

        query.setString("name", "Public");
        TermCategory categoryPublic = (TermCategory) query.iterate().next();

        query.setString("name", "Puget Sound Region");
        TermCategory categoryPSR = (TermCategory) query.iterate().next();

        query.setString("name", "Transportation Improvement Programming");
        TermCategory categoryTIP = (TermCategory) query.iterate().next();

        String[] csvFiles = getFiles();
        for (int i = 0; i < csvFiles.length; i++) {
          String fileName = csvFiles[i];
          System.out.println(" Process file " + fileName);

          BufferedReader in = new BufferedReader(new FileReader(fileName));

          String line;
          int count = 1;

          // first pass
          // read and reject the first line
          in.readLine();
          while ((line = in.readLine()) != null) {
            if ("".equals(line)) continue;
            String[] values = ((String[][]) ExcelCSVParser.parse(line))[0];

            System.out.println(" Line " + (++count) + "  --->  " + values[0]);

            Term term = new Term();

            // name
            term.setName(values[0].toUpperCase().trim());

            // short definition
            if (values.length > 1) {
              if (values[1].length() <= 0) { // copy from ext definition
                if (values[2].length() > 50) {
                  values[1] = values[2].substring(0, 47) + "...";
                } else {
                  values[1] = values[2];
                }
              }
              term.setShortDefinition(values[1]);
            }

            // ext definition
            if (values.length > 2) {
              term.setExtDefinition(values[2]);
            }

            // sources
            for (int j = 3; j < 6; j++) {
              if (values.length <= j) break;
              if (values[j] != null && !"".equals(values[j])) {
                TermSource source = new TermSource();
                source.setSource(values[j]);
                session.save(source);
                term.getSources().add(source);
              }
            } // for j

            // related terms
            // delay to another pass
            for (int j = 6; j < 11; j++) {
              if (values.length <= j) break;
            } // for j

            // links
            for (int j = 11; j < 14; j++) {
              if (values.length <= j) break;
              if (values[j] != null && !"".equals(values[j])) {
                TermLink link = new TermLink();
                link.setLink(values[j]);
                session.save(link);
                term.getLinks().add(link);
              }
            } // for j

            // Public Category
            if (values.length > 14 && "1".equals(values[14])) {
              term.getCategories().add(categoryPublic);
            }

            // Developer Category
            if (values.length > 15 && "1".equals(values[15])) {
              term.getCategories().add(categoryDeveloper);
            }

            // TIP Category
            if (values.length > 16 && "1".equals(values[16])) {
              term.getCategories().add(categoryTIP);
            }

            // TIP Category
            if (values.length > 17 && "1".equals(values[17])) {
              term.getCategories().add(categoryPSR);
            }

            session.save(term);
            // if (count==10) break;
          } // while first pass

          in.close();
          in = new BufferedReader(new FileReader(fileName));

          // second pass, process related terms
          // read and reject the first line
          in.readLine();
          count = 1;
          while ((line = in.readLine()) != null) {

            if ("".equals(line)) continue;
            String[] values = ((String[][]) ExcelCSVParser.parse(line))[0];
            // System.out.println(" Related terms, Line "+(++count)+"  --->  "+values[0]);

            query = session.createQuery("from Term where name=:name");
            query.setString("name", values[0].toUpperCase().trim());
            Term theTerm = (Term) query.iterate().next();

            for (int j = 6; j < 11; j++) {
              if (values.length > j && !"".equals(values[j].trim())) {
                String value = values[j].toUpperCase().trim();
                query = session.createQuery("from Term where name=:name");
                query.setString("name", value);
                // System.out.println("---> "+value);
                Iterator iter = query.iterate();
                if (iter.hasNext()) {
                  Term one = (Term) iter.next();
                  if (one != null) {
                    // System.out.println("found ---> "+one.getName());
                    theTerm.getRelatedTerms().add(one);
                    one.getRelatedTerms().add(theTerm);
                  }
                } else {
                  System.out.println("xxxx term " + value + " not found!");
                }
              }
            } // for j

            session.saveOrUpdate(theTerm);
          } // while second pass

          in.close();
        } // for iter

        transaction.commit();
      } catch (Exception ex) {
        ex.printStackTrace();
      } finally {
        session.close();
      }

      // initialization ends here

    } catch (Exception e) {
      throw new BuildException(e);
    }
  }
  public void testSQLFunctions() throws Exception {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Simple simple = new Simple();
    simple.setName("Simple 1");
    s.save(simple, new Long(10));

    if (getDialect() instanceof DB2Dialect) {
      s.find("from Simple s where repeat('foo', 3) = 'foofoofoo'");
      s.find("from Simple s where repeat(s.name, 3) = 'foofoofoo'");
      s.find("from Simple s where repeat( lower(s.name), 3 + (1-1) / 2) = 'foofoofoo'");
    }

    assertTrue(s.find("from Simple s where upper( s.name ) ='SIMPLE 1'").size() == 1);
    if (!(getDialect() instanceof HSQLDialect)) {
      assertTrue(
          s.find(
                      "from Simple s where not( upper( s.name ) ='yada' or 1=2 or 'foo'='bar' or not('foo'='foo') or 'foo' like 'bar' )")
                  .size()
              == 1);
    }
    if (!(getDialect() instanceof MySQLDialect)
        && !(getDialect() instanceof SybaseDialect)
        && !(getDialect() instanceof MckoiDialect)
        && !(getDialect() instanceof InterbaseDialect)
        && !(getDialect()
            instanceof TimesTenDialect)) { // My SQL has a funny concatenation operator
      assertTrue(
          s.find("from Simple s where lower( s.name || ' foo' ) ='simple 1 foo'").size() == 1);
    }
    if ((getDialect() instanceof SybaseDialect)) {
      assertTrue(
          s.find("from Simple s where lower( s.name + ' foo' ) ='simple 1 foo'").size() == 1);
    }
    if ((getDialect() instanceof MckoiDialect) || (getDialect() instanceof TimesTenDialect)) {
      assertTrue(
          s.find("from Simple s where lower( concat(s.name, ' foo') ) ='simple 1 foo'").size()
              == 1);
    }

    Simple other = new Simple();
    other.setName("Simple 2");
    other.setCount(12);
    simple.setOther(other);
    s.save(other, new Long(20));
    // s.find("from Simple s where s.name ## 'cat|rat|bag'");
    assertTrue(s.find("from Simple s where upper( s.other.name ) ='SIMPLE 2'").size() == 1);
    assertTrue(s.find("from Simple s where not ( upper( s.other.name ) ='SIMPLE 2' )").size() == 0);
    assertTrue(
        s.find(
                    "select distinct s from Simple s where ( ( s.other.count + 3 ) = (15*2)/2 and s.count = 69) or ( ( s.other.count + 2 ) / 7 ) = 2")
                .size()
            == 1);
    assertTrue(
        s.find(
                    "select s from Simple s where ( ( s.other.count + 3 ) = (15*2)/2 and s.count = 69) or ( ( s.other.count + 2 ) / 7 ) = 2 order by s.other.count")
                .size()
            == 1);
    Simple min = new Simple();
    min.setCount(-1);
    s.save(min, new Long(30));
    if (!(getDialect() instanceof MySQLDialect)
        && !(getDialect() instanceof HSQLDialect)) { // My SQL has no subqueries
      assertTrue(
          s.find("from Simple s where s.count > ( select min(sim.count) from Simple sim )").size()
              == 2);
      t.commit();
      t = s.beginTransaction();
      assertTrue(
          s.find(
                      "from Simple s where s = some( select sim from Simple sim where sim.count>=0 ) and s.count >= 0")
                  .size()
              == 2);
      assertTrue(
          s.find(
                      "from Simple s where s = some( select sim from Simple sim where sim.other.count=s.other.count ) and s.other.count > 0")
                  .size()
              == 1);
    }

    Iterator iter =
        s.iterate("select sum(s.count) from Simple s group by s.count having sum(s.count) > 10");
    assertTrue(iter.hasNext());
    assertTrue(new Integer(12).equals(iter.next()));
    assertTrue(!iter.hasNext());
    if (!(getDialect() instanceof MySQLDialect)) {
      iter = s.iterate("select s.count from Simple s group by s.count having s.count = 12");
      assertTrue(iter.hasNext());
    }

    s.iterate(
        "select s.id, s.count, count(t), max(t.date) from Simple s, Simple t where s.count = t.count group by s.id, s.count order by s.count");

    Query q = s.createQuery("from Simple s");
    q.setMaxResults(10);
    assertTrue(q.list().size() == 3);
    q = s.createQuery("from Simple s");
    q.setMaxResults(1);
    assertTrue(q.list().size() == 1);
    q = s.createQuery("from Simple s");
    assertTrue(q.list().size() == 3);
    q = s.createQuery("from Simple s where s.name = ?");
    q.setString(0, "Simple 1");
    assertTrue(q.list().size() == 1);
    q = s.createQuery("from Simple s where s.name = ? and upper(s.name) = ?");
    q.setString(1, "SIMPLE 1");
    q.setString(0, "Simple 1");
    q.setFirstResult(0);
    assertTrue(q.iterate().hasNext());
    q =
        s.createQuery(
            "from Simple s where s.name = :foo and upper(s.name) = :bar or s.count=:count or s.count=:count + 1");
    q.setParameter("bar", "SIMPLE 1");
    q.setString("foo", "Simple 1");
    q.setInteger("count", 69);
    q.setFirstResult(0);
    assertTrue(q.iterate().hasNext());
    q = s.createQuery("select s.id from Simple s");
    q.setFirstResult(1);
    q.setMaxResults(2);
    iter = q.iterate();
    int i = 0;
    while (iter.hasNext()) {
      assertTrue(iter.next() instanceof Long);
      i++;
    }
    assertTrue(i == 2);
    q = s.createQuery("select all s, s.other from Simple s where s = :s");
    q.setParameter("s", simple);
    assertTrue(q.list().size() == 1);

    q = s.createQuery("from Simple s where s.name in (:name_list) and s.count > :count");
    HashSet set = new HashSet();
    set.add("Simple 1");
    set.add("foo");
    q.setParameterList("name_list", set);
    q.setParameter("count", new Integer(-1));
    assertTrue(q.list().size() == 1);

    ScrollableResults sr = s.createQuery("from Simple s").scroll();
    sr.next();
    sr.get(0);
    sr.close();

    s.delete(other);
    s.delete(simple);
    s.delete(min);
    t.commit();
    s.close();
  }
Example #29
0
 public Iterator iterate(String queryString) {
   Query query = getSession().createQuery(queryString);
   return query.iterate();
 }
Example #30
0
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    Date todayDate = new Date();

    Session session = null;
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    session = sessionFactory.openSession();

    HttpSession httpSession = request.getSession(true);
    String LoggedInUserName = (String) httpSession.getAttribute("userName");

    if (request.getParameter("invitedBy") != null) {
      String invitedBy = request.getParameter("invitedBy");

      Transaction tr1 = session.beginTransaction();
      hibernate.GamesHistory newGame = new hibernate.GamesHistory();
      newGame.setUser1(LoggedInUserName);
      newGame.setUser2(invitedBy);
      newGame.setGameStatus("ongoing");
      newGame.setStartDate(todayDate);
      session.save(newGame);

      tr1.commit();

      String SQL_QUERY =
          "from GamesHistory game where game.user1='"
              + LoggedInUserName
              + "' AND user2='"
              + invitedBy
              + "' order by game.startDate DESC";

      Query query = session.createQuery(SQL_QUERY);
      query.setMaxResults(1);
      int gameId = 0;
      for (Iterator it = query.iterate(); it.hasNext(); ) {
        GamesHistory gameObject = (GamesHistory) it.next();
        gameId = gameObject.getGameId();
      }

      GameMovesStore newGameMovesStore = new GameMovesStore();
      newGameMovesStore.setNewGameMoveMap(gameId);

      request.setAttribute("invitedBy", invitedBy);
      request.setAttribute("gameId", gameId);

      session.flush();

      UsersDao newUsersDao = new UsersDao();
      newUsersDao.setUserBusy(LoggedInUserName);
      newUsersDao.setUserBusy(invitedBy);
    }

    if (request.getParameter("invited") != null) {
      String invited = request.getParameter("invited");

      String SQL_QUERY =
          "from GamesHistory game where game.user1='"
              + invited
              + "' AND user2='"
              + LoggedInUserName
              + "' order by game.startDate DESC";

      Query query = session.createQuery(SQL_QUERY);
      query.setMaxResults(1);
      int gameId = 0;
      for (Iterator it = query.iterate(); it.hasNext(); ) {
        GamesHistory gameObject = (GamesHistory) it.next();
        gameId = gameObject.getGameId();
      }

      request.setAttribute("gameId", gameId);
      request.setAttribute("invited", invited);
    }

    session.close();

    InvitationBean newInvitationBean = new InvitationBean();
    newInvitationBean.deleteUserInvitationMap(LoggedInUserName);
    return mapping.findForward("success");
  }