示例#1
0
 /**
  * 将finder中的参数设置到query中。
  *
  * @param query
  */
 public Query setParamsToQuery(Query query) {
   if (params != null) {
     for (int i = 0; i < params.size(); i++) {
       if (types.get(i) == null) {
         query.setParameter(params.get(i), values.get(i));
       } else {
         query.setParameter(params.get(i), values.get(i), types.get(i));
       }
     }
   }
   if (paramsList != null) {
     for (int i = 0; i < paramsList.size(); i++) {
       if (typesList.get(i) == null) {
         query.setParameterList(paramsList.get(i), valuesList.get(i));
       } else {
         query.setParameterList(paramsList.get(i), valuesList.get(i), typesList.get(i));
       }
     }
   }
   if (paramsArray != null) {
     for (int i = 0; i < paramsArray.size(); i++) {
       if (typesArray.get(i) == null) {
         query.setParameterList(paramsArray.get(i), valuesArray.get(i));
       } else {
         query.setParameterList(paramsArray.get(i), valuesArray.get(i), typesArray.get(i));
       }
     }
   }
   return query;
 }
示例#2
0
 public User getUser(String username, String psd) {
   Session session = sessionFactory.getCurrentSession();
   Query q = session.createQuery(" from User u where username= :username and psd = :psd");
   q.setParameter("username", username);
   q.setParameter("psd", psd);
   return (User) q.uniqueResult();
 }
示例#3
0
  public int getCountOfSubscribers(int forumId, int userId) {
    // TODO Auto-generated method stub
    Session session = this.sessionFactory.openSession();
    Transaction tx = null;
    int countOfSubscribers = 0;
    try {
      tx = session.beginTransaction();
      Query query = null;
      if (userId == 0) {
        query = session.createQuery("select count(*) from Subscription where forumId = :forumId");
        query.setParameter("forumId", forumId);
      } else {
        query =
            session.createQuery(
                "select count(*) from Subscription where forumId = :forumId and userId = :userId");
        query.setParameter("forumId", forumId);
        query.setParameter("userId", userId);
      }

      Long count = (Long) query.uniqueResult();
      countOfSubscribers = count.intValue();
      // System.out.println("No of subscribers.."+countOfSubscribers);
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return countOfSubscribers;
  }
示例#4
0
 public void deleteMessage(int fromId, long messageId) {
   String sql = "delete from Message where fromid=? and id=?";
   Query query = this.getQuery(sql);
   query.setParameter(0, fromId);
   query.setParameter(1, messageId);
   query.executeUpdate();
 }
示例#5
0
  @SuppressWarnings("unchecked")
  public List<OrdemServico> listarOrdemFaturamentoAFaturar(
      final Pessoa cliente, final Date de, final Date ate) {
    StringBuilder sb =
        new StringBuilder(
            "SELECT h FROM "
                + entityClass.getName()
                + " h WHERE (h.dataFinalizacao IS NOT NULL) AND (h.cliente = :cliente) AND (h.unidadePai IS NULL) AND (h.notaFiscalSaida.dtEmissao BETWEEN :dataDe AND :dataAte) AND (h.faturamento IS NULL) ORDER BY h.numeroOrdemServico");
    Query query = sessionFactory.getCurrentSession().createQuery(sb.toString());

    query.setParameter("cliente", cliente);

    if (de != null) {
      query.setParameter("dataDe", de);
    } else {
      query.setParameter("dataDe", new Date(0));
    }

    if (ate != null) {
      query.setParameter("dataAte", DateUtils.nextDay(ate));
    } else {
      query.setParameter("dataAte", DateUtils.nextDay(new Date()));
    }
    return query.list();
  }
示例#6
0
	public void processSelection(NodeSelectedEvent event) {
		try {
			HtmlTree tree = (HtmlTree) event.getComponent();
			Department bean = (Department) tree.getRowData();
			ID_ = bean.getID_();
			selectRecordById(String.valueOf(ID_));
			orgId = bean.getOrgId();
			parentId = bean.getParentId();
			orgName = bean.getOrgName();
			parentName = bean.getParentName();
			if (FunctionLib.isNum(getMySession().getTempStr().get("Department.move.id"))) {
				Query query = getSession().getNamedQuery("core.department.moverecordbyid");
				query.setParameter("mId", 0);
				query.setParameter("orgId", orgId);
				query.setParameter("parentId", ID_);
				query.setParameter("id", getMySession().getTempStr().get("Department.move.id"));
				query.executeUpdate();
				query = null;
				getMySession().getTempStr().put("Department.move.id", "");

				query = getSession().createSQLQuery("CALL of_update_group(:id)");
				query.setParameter("id", getMySession().getTempStr().get("Department.move.id"));
				query.executeUpdate();

				FunctionLib.refresh();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
示例#7
0
  @Override
  @SuppressWarnings("unchecked")
  public BDRSWurflCapability getByNameValue(
      Session sesh, String capabilityName, String capabilityValue) {
    String query = "select c from BDRSWurflCapability c where c.value = :value and c.name = :name";
    Query q;
    if (sesh == null) {
      q = getSession().createQuery(query);
    } else {
      q = sesh.createQuery(query);
    }

    q.setParameter("value", capabilityValue);
    q.setParameter("name", capabilityName);

    List<BDRSWurflCapability> capList = q.list();
    if (capList.size() > 0) {
      if (capList.size() > 1) {
        log.warn(
            "Found Multiple BDRSWurflCapabilities for values : "
                + capabilityName
                + ", "
                + capabilityValue);
      }
      return capList.get(0);
    }
    return null;
  }
 @Override
 @Transactional
 public String updateDomainApplicationPlanMappingDetails(
     DomainApplicationPlanMapping domainApplicationPlanMapping, Long subscriptionId)
     throws Exception {
   String result = null;
   try {
     Query query =
         sessionFactory
             .getCurrentSession()
             .createQuery(
                 "update DomainApplicationPlanMapping set PLAN_START_DATE=:startDate,PLAN_EXPIRY_DATE=:endDate,UPDATED_DATE=:updatedDate,"
                     + "UPDATED_BY=:updatedBy where SUBSCRIPTION_ID=:subId");
     query.setParameter("startDate", domainApplicationPlanMapping.getPlanStartDate());
     query.setParameter("endDate", domainApplicationPlanMapping.getPlanExpiryDate());
     query.setParameter("updatedDate", domainApplicationPlanMapping.getUpdatedDate());
     query.setParameter("updatedBy", domainApplicationPlanMapping.getUpdatedBy());
     query.setParameter("subId", subscriptionId);
     query.executeUpdate();
   } catch (Exception e) {
     result = e.getMessage();
     e.printStackTrace();
     throw e;
   }
   return result;
 }
示例#9
0
  @SuppressWarnings("unchecked")
  private List<StudentQuestion> getChildApplyQuestionCodes(Session session, String c_Code) {

    Query query =
        session.createQuery(
            "select q.studentCode,question "
                + "from StudentAndQuestion as q , QuestionBank as question"
                + " where q.guard = ? and q.studentCode = ? "
                + " and q.questionCode = question.code order by q.studentCode");
    query.setParameter(0, StudentQuestionStatus.ApplyAndNotApprove);
    query.setParameter(1, c_Code);
    List<Object[]> datas = query.list();
    List<StudentQuestion> result = new ArrayList<StudentQuestion>();
    StudentQuestion sq = new StudentQuestion(new Student(c_Code), null);
    result.add(sq);
    for (Object[] data : datas) {
      if (data.length >= 2) {
        Question q =
            QuestionManager.GetInstance().CreateQuestionByQuestionBank((QuestionBank) data[1]);
        result.get(0).getQuestions().add(q);
      }
    }

    return result;
  }
示例#10
0
  /**
   * Aggregate all income receipt for given period The result format is:
   * Map<accountId,'accountName|amount'>
   *
   * @param from
   * @param to
   * @return
   */
  public Map<Integer, Object[]> aggregateIncomeReceiptItem(Date from, Date to) {
    String squery =
        "select ir.account.id, ir.account.name, sum(ir.amount) from IncomeReceiptItem  as ir "
            + " left join ir.receipt as  r  "
            + "where r.receiptDate >= :from and r.receiptDate <= :to "
            + " group by ir.account.name";

    Query query = sessionFactory.getCurrentSession().createQuery(squery);
    query.setParameter("from", from);
    query.setParameter("to", to);
    List result = query.list();
    Map<Integer, Object[]> mapResult = new HashMap<Integer, Object[]>();
    String accountName;
    BigDecimal amount;
    Integer accountId;
    String tmp;
    if (result != null && result.size() > 0) {
      for (Object o : result) {
        Object[] obj = (Object[]) o;
        accountId = NumberUtils.toInt(obj[0].toString());
        mapResult.put(accountId, obj);
      }
    }
    return mapResult;
  }
  @Test
  public void basicCRUD() {
    try {
      Actor actor = new Actor();
      actor.setFirstName("Arnold");
      actor.setLastName("Schwarzenegger");
      actor.setNickName("Arnie");
      Date date1 = new SimpleDateFormat("MM/dd/yy").parse("06/30/47");
      actor.setBirthDate(date1);

      getSession().save(actor);

      Query query = getSession().createQuery("from Actor where nickname=:nickname");
      query.setParameter("nickname", "Arnie");

      Actor arnie = (Actor) query.uniqueResult();
      assertEquals(2, arnie.getId());
      arnie.setNickName("Big Guy");
      getSession().save(arnie);

      query.setParameter("nickname", "Big Guy");
      Actor arnie2 = (Actor) query.uniqueResult();
      assertEquals("Version should match", 1, arnie2.getVersion());

      getSession().delete(actor);
      Actor arnie3 = (Actor) query.uniqueResult();
      assertEquals("Arnie should no longer exist!", null, arnie3);

    } catch (Exception ex) {
      logger.error("Excption thrown: ", ex.getMessage());
      assertTrue(ex.getMessage(), false);
      ex.printStackTrace();
    }
  }
  @Override
  public List<MenuItem> getMenuItems(
      List<Integer> roleIds, Integer sequence, String parentMenuUid) {
    String hql =
        "SELECT distinct menuItem FROM MenuItem menuItem join menuItem.menu.menuRoleAssocs menuRoleAssoc  WHERE 1=1 ";
    if (roleIds != null) {
      hql += " AND menuRoleAssoc.role.roleId IN ( :roleIds )";
    }
    if (parentMenuUid != null) {
      hql += " AND menuItem.parentMenuUid =:parentMenuUid";
    }
    if (sequence != null) {
      hql += " AND menuItem.sequence =:sequence";
    }
    if (parentMenuUid == null) {
      hql += " AND menuItem.parentMenuUid is null";
    }
    hql += " ORDER BY menuItem.sequence";

    Query query = getSession().createQuery(hql);
    if (roleIds != null) {
      query.setParameterList("roleIds", roleIds);
    }
    if (parentMenuUid != null) {
      query.setParameter("parentMenuUid", parentMenuUid);
    }
    if (sequence != null) {
      query.setParameter("sequence", sequence);
    }
    return query.list();
  }
  /**
   * Binds a parameter value to a query parameter.
   *
   * @param parameter the report parameter
   */
  protected void setParameter(JRValueParameter parameter) {
    String hqlParamName = getHqlParameterName(parameter.getName());
    Class<?> clazz = parameter.getValueClass();
    Object parameterValue = parameter.getValue();

    if (log.isDebugEnabled()) {
      log.debug(
          "Parameter " + hqlParamName + " of type " + clazz.getName() + ": " + parameterValue);
    }

    Type type = hibernateTypeMap.get(clazz);

    if (type != null) {
      query.setParameter(hqlParamName, parameterValue, type);
    } else if (Collection.class.isAssignableFrom(clazz)) {
      query.setParameterList(hqlParamName, (Collection<?>) parameterValue);
    } else {
      if (session.getSessionFactory().getClassMetadata(clazz)
          != null) // param type is a hibernate mapped entity
      {
        query.setEntity(hqlParamName, parameterValue);
      } else // let hibernate try to guess the type
      {
        query.setParameter(hqlParamName, parameterValue);
      }
    }
  }
  @SuppressWarnings("unchecked")
  public List<Documento> findByNomeAndCategoriaDocumentoByUsuario(
      String nome, CategoriaDocumento categoriaDocumento, Usuario usuario) {
    StringBuilder hql = new StringBuilder();
    hql.append("FROM Documento documento WHERE ");
    if (categoriaDocumento != null) {
      hql.append("documento.categoriaDocumento = :tipo AND ");
    }
    if (nome != null && !nome.isEmpty()) {
      hql.append("documento.nome LIKE '%");
      hql.append(nome);
      hql.append("%' AND ");
    }

    hql.append("documento.categoriaDocumento.usuario.id = :idUsuario ORDER BY documento.nome ASC");

    Query hqlQuery = getQuery(hql.toString());
    if (categoriaDocumento != null) {
      hqlQuery.setParameter("tipo", categoriaDocumento);
    }

    hqlQuery.setParameter("idUsuario", usuario.getId());

    return hqlQuery.list();
  }
示例#15
0
	/**
	 * 更新一条记录
	 */
	public void updateRecordById() {
		try {
			Map<?, ?> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
			String orgId = (String) params.get("orgId");
			String parentId = (String) params.get("parentId");
			String id = (String) params.get("id");
			if (!FunctionLib.isNum(orgId) || !FunctionLib.isNum(parentId) || !FunctionLib.isNum(id))
				return;
			if ("".equals(depaName)) {
				String msg = getLang().getProp().get(getMySession().getL()).get("name") + getLang().getProp().get(getMySession().getL()).get("cannotbenull");
				getMySession().setMsg(msg, 2);
				return;
			}
			Query query = getSession().getNamedQuery("core.department.updaterecordbyid");
			query.setParameter("mId", 0);
			query.setParameter("depaName", depaName);
			query.setParameter("depaDesc", depaDesc);
			query.setParameter("sequence", sequence);
			query.setParameter("id", id);
			query.executeUpdate();
			query = null;

			query = getSession().getNamedQuery("core.department.of.update");
			query.setParameter("id", id);
			query.executeUpdate();

			String msg = getLang().getProp().get(getMySession().getL()).get("success");
			getMySession().setMsg(msg, 1);
		} catch (Exception ex) {
			String msg = getLang().getProp().get(getMySession().getL()).get("faield");
			getMySession().setMsg(msg, 2);
			ex.printStackTrace();
		}
	}
示例#16
0
  /**
   * Returns a list of all active and finished one time orders going back n number of months,
   * containing the given item id for the given user.
   *
   * @param userId user id of orders
   * @param itemId item id of order lines
   * @param months previous number of months to include (1 = this month plus the previous)
   * @return list of found one-time orders, empty list if none found
   */
  @SuppressWarnings("unchecked")
  public List<OrderLineDTO> findOnetimeByUserItem(Integer userId, Integer itemId, Integer months) {
    final String hql =
        "select line "
            + "  from OrderLineDTO line "
            + "where line.deleted = 0 "
            + "  and line.item.id = :itemId "
            + "  and line.purchaseOrder.baseUserByUserId.id = :userId "
            + "  and line.purchaseOrder.orderPeriod.id = :period "
            + "  and (line.purchaseOrder.orderStatus.orderStatusFlag = :active_status"
            + "       or line.purchaseOrder.orderStatus.orderStatusFlag = :finished_status)"
            + "  and line.purchaseOrder.deleted = 0 "
            + "  and line.purchaseOrder.createDate > :startdate";

    Query query = getSession().createQuery(hql);
    query.setParameter("itemId", itemId);
    query.setParameter("userId", userId);
    query.setParameter("period", ServerConstants.ORDER_PERIOD_ONCE);
    query.setParameter("active_status", OrderStatusFlag.INVOICE.ordinal());
    query.setParameter("finished_status", OrderStatusFlag.FINISHED.ordinal());

    DateMidnight startdate = new DateMidnight().minusMonths(months);
    query.setParameter("startdate", startdate.toDate());

    return query.list();
  }
示例#17
0
	/*
	 * * Tree Node
	 * 
	 * @param parentCode
	 * 
	 * @param node
	 */
	@SuppressWarnings("unchecked")
	public void addNodes(TreeNode<Department> node, int orgId, int parentId, String oName, String pName) {
		try {
			Query query = getSession().getNamedQuery("core.department.getchildren");
			query.setParameter("orgId", orgId);
			query.setParameter("parentId", parentId);
			Iterator<?> it = query.list().iterator();
			int id;
			String name, desc;
			while (it.hasNext()) {
				Object obj[] = (Object[]) it.next();
				id = 0;
				name = desc = "";
				if (obj[0] != null)
					id = Integer.valueOf(String.valueOf(obj[0]));
				if (obj[1] != null)
					name = String.valueOf(obj[1]);
				if (obj[2] != null)
					desc = String.valueOf(obj[2]);
				@SuppressWarnings("rawtypes")
				TreeNodeImpl nodeImpl = new TreeNodeImpl();
				nodeImpl.setData(new Department(orgId, id, id, oName, pName, name, desc));
				node.addChild(key, nodeImpl);
				key++;
				if (hasChild(orgId, id))
					addNodes(nodeImpl, orgId, id, oName, name);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
示例#18
0
  public PaymentInvoice getPaymentInvoice(int transId) throws CustomerException {
    if (id <= 0) {
      throw new CustomerException("Invalid Customer...Id cannot be <= 0");
    }
    if (transId == 0) {
      throw new PaymentException("Please specify a transaction to look up an invoice against");
    }
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();

    PaymentInvoice paymentInvoice = new PaymentInvoice();

    Query q = session.getNamedQuery("fetch_pmt_invoice");
    q.setParameter("in_cust_id", getId());
    q.setParameter("in_trans_id", transId);
    List<PaymentInvoice> paymentInvoiceList = q.list();
    if (paymentInvoiceList != null && paymentInvoiceList.size() > 0) {
      for (PaymentInvoice tempPaymentInvoice : paymentInvoiceList) {
        paymentInvoice = tempPaymentInvoice;
      }
    }
    session.getTransaction().commit();
    // session.close();
    return paymentInvoice;
  }
示例#19
0
	public void addChildren(String parentKey, int orgId, int parentId, String oName, String pName) {
		try {
			level++;
			Query query = getSession().getNamedQuery("core.department.getchildren");
			query.setParameter("orgId", orgId);
			query.setParameter("parentId", parentId);
			Iterator<?> it = query.list().iterator();
			int id;
			String name;
			int i = 1;
			while (it.hasNext()) {
				Object obj[] = (Object[]) it.next();
				id = 0;
				name = "";
				if (obj[0] != null)
					id = Integer.valueOf(String.valueOf(obj[0]));
				if (obj[1] != null)
					name = String.valueOf(obj[1]);
				bf.append(parentKey + "." + i + "=depa," + id + "," + FunctionLib.gb23122Unicode(name) + "\r\n");

				if (hasChild(orgId, id))
					addChildren(parentKey + "." + i, orgId, id, oName, name);
				i++;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
  /**
   * Method is used to save presenter material details in db
   *
   * @param session
   * @param pCode presenter code
   * @param op (INSERT/UPDATE)
   * @param HttpServletRequest requestParameters
   * @param pCode
   * @param byteSession
   * @param field_name
   */
  public void storeMaterialToDB(
      Session session,
      int pCode,
      String op,
      HttpServletRequest requestParameters,
      String byteSession,
      String file_name,
      String field_name) {

    try {

      if (op.equals("UPDATE")) {
        Query deleteQ =
            session.createQuery(
                "delete PresenterMaterial where presenterCode =:presenterCode and fieldName =:fieldName");
        deleteQ.setParameter("presenterCode", pCode);
        deleteQ.setParameter("fieldName", field_name);
        deleteQ.executeUpdate();
      }
      PresenterMaterial preMat = null;
      byte[] bytearray = (byte[]) requestParameters.getSession().getAttribute(byteSession);
      if (pCode > 0) {
        preMat = new PresenterMaterial();
        preMat.setPresenterCode(pCode);
        preMat.setMaterialName(file_name);
        preMat.setFieldName(field_name);
        preMat.setMaterial(bytearray);
        session.save(preMat);
      }
      log.log(Level.INFO, "---PresenterMaintenance Upload Material  Done---");
    } catch (Exception e) {
      e.printStackTrace();
      log.log(Level.SEVERE, e.getMessage());
    }
  }
示例#21
0
 @SuppressWarnings("unchecked")
 @Override
 public Users checkUsers(Users users) {
   // TODO Auto-generated method stub
   try {
     String queryString = "from Users as model where model.account= ? and model.password= ?";
     Query queryObject = getCurrentSession().createQuery(queryString);
     queryObject.setParameter(0, users.getAccount());
     queryObject.setParameter(1, users.getPassword());
     List<Users> results = queryObject.list();
     if (results.size() > 0) {
       Timestamp tt = new Timestamp(System.currentTimeMillis());
       queryString = "update Users as model set model.logintime= ? where model.account= ?";
       Query query = this.getCurrentSession().createQuery(queryString);
       query.setParameter(0, tt);
       query.setParameter(1, users.getAccount());
       query.executeUpdate();
       return (Users) results.get(0);
     } else {
       return null;
     }
   } catch (Exception e) {
     System.out.println("getusers error:" + e.getMessage());
     return null;
   }
 }
 public List<SalFactD> getFactDetails(Map qo) {
   StringBuilder sb = new StringBuilder();
   sb.append("select sfd from SalFactD sfd")
       .append(" left outer join fetch sfd.id.fact sf")
       .append(" left outer join fetch sfd.id.item si")
       .append(" left outer join fetch sfd.person p")
       .append(" where 1 = 1");
   if (qo != null) {
     if (qo.containsKey("branch.id")) sb.append(" and sf.id.branch.id = :branchId");
     if (qo.containsKey("fact.no")) sb.append(" and sf.id.no = :factNo");
     if (qo.containsKey("depart.id")) sb.append(" and sf.depart.id = :departId");
     if (qo.containsKey("person.id")) sb.append(" and sfd.person.id = :personId");
     if (qo.containsKey("persons")
         && qo.get("persons") != null
         && ((List) qo.get("persons")).size() > 0) sb.append(" and sfd.person.id in (:persons)");
   }
   sb.append(" order by sf.id.branch.id, sf.depart.id, sf.id.no, sfd.id.no, si.no");
   Query q = getSession().createQuery(sb.toString());
   if (qo != null) {
     if (qo.containsKey("branch.id")) q.setParameter("branchId", qo.get("branch.id"));
     if (qo.containsKey("fact.no")) q.setParameter("factNo", qo.get("fact.no"));
     if (qo.containsKey("depart.id")) q.setParameter("departId", qo.get("depart.id"));
     if (qo.containsKey("person.id")) q.setParameter("personId", qo.get("person.id"));
     if (qo.containsKey("persons")
         && qo.get("persons") != null
         && ((List) qo.get("persons")).size() > 0)
       q.setParameterList("persons", (List) qo.get("persons"));
   }
   return (List<SalFactD>) q.list();
 }
示例#23
0
  @SuppressWarnings("unchecked")
  public OrdemServico montarConjunto(final Long id) {
    Query q =
        sessionFactory
            .getCurrentSession()
            .createQuery(
                "SELECT h FROM "
                    + entityClass.getName()
                    + " h "
                    + "LEFT JOIN FETCH h.unidadePai u "
                    + "LEFT JOIN FETCH h.reparo rep "
                    + "LEFT JOIN FETCH h.orcamento orc "
                    + "WHERE h.id=:id");
    q.setParameter("id", id);
    OrdemServico r = (OrdemServico) q.uniqueResult();

    Query q2 =
        sessionFactory
            .getCurrentSession()
            .createQuery(
                "SELECT h FROM "
                    + entityClass.getName()
                    + " h "
                    + "LEFT JOIN FETCH h.unidadePai u "
                    + "LEFT JOIN FETCH h.reparo rep "
                    + "LEFT JOIN FETCH h.orcamento orc "
                    + "WHERE h.unidadePai.id=:id");
    q2.setParameter("id", id);
    List<OrdemServico> pFilhas = q2.list();

    r.setPlacasFilhas(new HashSet<OrdemServico>());
    r.getPlacasFilhas().addAll(pFilhas);
    return r;
  }
示例#24
0
  public void removePlayerFromLeague(League league, Player player) {
    //		List<PlayerLeague> playerLeagues = hibernateTemplate.find(getPlayerLeagueQuery("", "where
    // playerleague.player.id=? and playerleague.league.id=?"),
    //				new Object[] {player.getId(), league.getId()});
    //		if (!playerLeagues.isEmpty())
    //		{
    //		 hibernateTemplate.delete(playerLeagues.iterator().next());
    //		}
    //		if (!playerLeagues.isEmpty())
    //		{
    //			dao.delete(playerLeagues.iterator().next());
    //		}

    Query query =
        getQuery(
            getPlayerLeagueQuery(
                "", "where playerleague.player.id=? and playerleague.league.id=?"));
    query.setParameter(0, player.getId());
    query.setParameter(1, league.getId());

    List<PlayerLeague> playerLeagues = query.list();

    for (PlayerLeague playerLeague : playerLeagues) {
      Query query2 = getQuery("delete from playerLeague where id = ?");
      query2.setParameter(0, playerLeague.getId());

      query2.executeUpdate();
    }
  }
  @RequestMapping(value = "convert")
  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public String validateImages() throws Exception {
    final Session session = sessionFactory.getCurrentSession();
    final Query query =
        session.createQuery(
            "select id, name from billiongoods.server.warehouse.impl.HibernateCategory");
    final List list = query.list();
    for (Object o : list) {
      final Object[] v = (Object[]) o;

      final Integer id = (Integer) v[0];
      final String name = (String) v[1];

      final String s = symbolicConverter.generateSymbolic(name);

      final Query query1 =
          session.createQuery(
              "update billiongoods.server.warehouse.impl.HibernateCategory set symbolic=:n where id=:id");
      query1.setParameter("id", id);
      query1.setParameter("n", s);
      query1.executeUpdate();
    }
    return "/content/maintain/main";
  }
示例#26
0
  @Override
  public List<Paciente> filtrarPaciente(Paciente paciente) throws SystemException {

    String sql = "SELECT p FROM Paciente p WHERE 1=1 ";
    StringBuffer buffer = new StringBuffer(sql);

    if (!StringUtil.ehBrancoOuNulo(paciente.getNomePaciente())) {
      buffer.append("AND upper(p.nomePaciente) like upper(:nome) ");
    }

    if (!StringUtil.ehBrancoOuNulo(paciente.getCodigoCarteira())) {
      buffer.append("AND p.codigoCarteira = :carteira ");
    }

    Query query = getSession().createQuery(buffer.toString());

    if (!StringUtil.ehBrancoOuNulo(paciente.getNomePaciente())) {
      query.setParameter("nome", "%" + paciente.getNomePaciente() + "%");
    }

    if (!StringUtil.ehBrancoOuNulo(paciente.getCodigoCarteira())) {
      query.setParameter("carteira", paciente.getCodigoCarteira());
    }

    return (List<Paciente>) query.list();
  }
示例#27
0
 @Override
 public void deleteSubscription(int userId, int forumId) {
   // TODO Auto-generated method stub
   Session session = this.sessionFactory.openSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Query query =
         session.createQuery(
             "delete from Subscription where userId = :userId and forumId = :forumId");
     query.setParameter("userId", userId);
     query.setParameter("forumId", forumId);
     int result = query.executeUpdate();
     System.out.println("Execute query..");
     if (result > 0) {
       tx.commit();
       // System.out.println("Subscription Removed..");
     } else {
       // System.out.println("Subscription does not exist");
       tx.rollback();
     }
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
 }
  @Override
  public void getPortalEvents(
      DateTime startTime,
      DateTime endTime,
      int maxEvents,
      FunctionWithoutResult<PortalEvent> handler) {
    final Session session = this.getEntityManager().unwrap(Session.class);
    final org.hibernate.Query query = session.createQuery(this.selectQuery);
    query.setParameter(this.startTimeParameter.getName(), startTime);
    query.setParameter(this.endTimeParameter.getName(), endTime);
    if (maxEvents > 0) {
      query.setMaxResults(maxEvents);
    }

    for (final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
        results.next(); ) {
      final PersistentPortalEvent persistentPortalEvent = (PersistentPortalEvent) results.get(0);
      final PortalEvent portalEvent =
          this.toPortalEvent(
              persistentPortalEvent.getEventData(), persistentPortalEvent.getEventType());
      handler.apply(portalEvent);
      persistentPortalEvent.setAggregated(true);
      session.evict(persistentPortalEvent);
    }
  }
示例#29
0
  public Pager findAllUnconfirmedByProbationUnitId(
      String referenceId, Integer start, Integer size) {
    Pager pager = new Pager();

    start = (start == null) ? 0 : start;
    pager.setStart(start);

    size = (size == null) ? Pager.DEFAULT_PAGE_SIZE : size;
    pager.setSize(size);

    Query queryCount =
        getSession()
            .createQuery(
                "select count(ct) from ChildTransfer ct,LamaNivasa tl,ProbationUnit p where ct.toLamaNivasaId.id = tl.id and tl.probationUnit.id=p.id and p.id= :pid and ct.status=0");
    queryCount.setParameter("pid", referenceId);
    int listCount = ((Long) queryCount.uniqueResult()).intValue();
    pager.setTotal(listCount);

    Query query =
        getSession()
            .createQuery(
                "select ct from ChildTransfer ct,LamaNivasa tl,ProbationUnit p where ct.toLamaNivasaId.id = tl.id and tl.probationUnit.id=p.id and p.id= :pid and ct.status=0");

    query.setParameter("pid", referenceId);
    query.setFirstResult(start);
    query.setMaxResults(size);
    @SuppressWarnings("unchecked")
    List<ChildTransfer> list = query.list();

    pager.setList(list);

    return pager;
  }
示例#30
0
  @SuppressWarnings("unchecked")
  public NotaFiscalRemessa buscarPorIdListagemNotaFiscalSaida(final Long id) {
    Query q =
        sessionFactory
            .getCurrentSession()
            .createQuery(
                "SELECT h "
                    + "FROM "
                    + entityClass.getName()
                    + " h "
                    + "LEFT JOIN FETCH h.ordensServico os "
                    + "LEFT JOIN FETCH h.volumes "
                    + "LEFT JOIN FETCH h.cliente c "
                    + "LEFT JOIN FETCH c.enderecos  "
                    + "WHERE h.id=:id");
    q.setParameter("id", id);
    NotaFiscalRemessa r = (NotaFiscalRemessa) q.uniqueResult();

    Query q2 =
        sessionFactory
            .getCurrentSession()
            .createQuery(
                "SELECT o FROM OrdemServico o "
                    + "WHERE o.notaFiscalSaida.id = :id  ORDER BY o.id");
    q2.setParameter("id", id);

    List<OrdemServico> oss = q2.list();

    if (oss != null) {
      r.setOrdensServico(new HashSet<OrdemServico>());
      r.getOrdensServico().addAll(oss);
    }
    return r;
  }