/**
   * Find all News entities with a specific property value.
   *
   * @param propertyName the name of the News property to query
   * @param value the property value to match
   * @param rowStartIdxAndCount Optional int varargs. rowStartIdxAndCount[0] specifies the the row
   *     index in the query result-set to begin collecting the results. rowStartIdxAndCount[1]
   *     specifies the the maximum number of results to return.
   * @return List<News> found by query
   */
  @SuppressWarnings("unchecked")
  public List<News> findByProperty(
      String propertyName, final Object value, final int... rowStartIdxAndCount) {
    LogUtil.log(
        "finding News instance with property: " + propertyName + ", value: " + value,
        Level.INFO,
        null);
    try {
      final String queryString =
          "select model from News model where model." + propertyName + "= :propertyValue";
      Query query = entityManager.createQuery(queryString);
      query.setParameter("propertyValue", value);
      if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
        int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
        if (rowStartIdx > 0) {
          query.setFirstResult(rowStartIdx);
        }

        if (rowStartIdxAndCount.length > 1) {
          int rowCount = Math.max(0, rowStartIdxAndCount[1]);
          if (rowCount > 0) {
            query.setMaxResults(rowCount);
          }
        }
      }
      return query.getResultList();
    } catch (RuntimeException re) {
      LogUtil.log("find by property name failed", Level.SEVERE, re);
      throw re;
    }
  }
  /**
   * Deletes all Results and ResultSets of a test, selftest or survey
   *
   * @param olatRes
   * @param olatResDet
   * @param repRef
   * @return deleted ResultSets
   */
  public int deleteAllResults(Long olatRes, String olatResDet, Long repRef) {
    StringBuilder sb = new StringBuilder();
    sb.append("select rset from ").append(QTIResultSet.class.getName()).append(" as rset ");
    sb.append(
        " where rset.olatResource=:resId and rset.olatResourceDetail=:resSubPath and rset.repositoryRef=:repoKey ");

    EntityManager em = dbInstance.getCurrentEntityManager();
    List<QTIResultSet> sets =
        em.createQuery(sb.toString(), QTIResultSet.class)
            .setParameter("resId", olatRes)
            .setParameter("resSubPath", olatResDet)
            .setParameter("repoKey", repRef)
            .getResultList();

    StringBuilder delSb = new StringBuilder();
    delSb
        .append("delete from ")
        .append(QTIResult.class.getName())
        .append(" as res where res.resultSet.key=:setKey");
    Query delResults = em.createQuery(delSb.toString());
    for (QTIResultSet set : sets) {
      delResults.setParameter("setKey", set.getKey()).executeUpdate();
      em.remove(set);
    }
    return sets.size();
  }
  public int findUserVisitsNo(Integer userId) {
    Query q = em.createNamedQuery("findUserVisitsNo");
    q.setParameter("userId", userId);

    int result = (int) q.getSingleResult();
    return result;
  }
 public void _endpoint_clear_rest(CommandInterpreter commandInterpreter) {
   this.em.getTransaction().begin();
   Query query = this.em.createQuery("DELETE FROM RESTEndpoint");
   int deletedREST = query.executeUpdate();
   commandInterpreter.println("Deleted " + deletedREST + " RESTEndpoints.");
   this.em.getTransaction().commit();
 }
Example #5
0
 /**
  * Liste aller Lehrer abfragen
  *
  * @return List der Lehrer
  */
 @GET
 public List<Lehrer> getAllLehrer() {
   Log.d("Webservice Lehrer Get:");
   Query query = em.createNamedQuery("findAllTeachers");
   List<Lehrer> lehrer = query.getResultList();
   return lehrer;
 }
 public Object[] readDbValueForContinentAndExpired(String isoCode) {
   Query query =
       this.entityManager.createNativeQuery(
           "select CONTINENT, EXPIRED from " + Country.TABLE_NAME + " where ISO_CODE=?");
   query.setParameter(1, isoCode);
   return (Object[]) query.getSingleResult();
 }
  /** @return */
  private ArrayList<ReferenceDataRefDataType> getUsedRefSpecialtySchemes() {
    System.out.println("\n========> Getting Used specialtyscheme references");

    ArrayList<ReferenceDataRefDataType> refColl = new ArrayList<ReferenceDataRefDataType>();
    Query query = null;
    int startRec = refDetails.getStartingRecNumber();
    int maxDisplay = refDetails.getMaxRecordsToShow();

    if ((refDetails.getLookupSystem().getCodeSystem() == null)
        || (refDetails.getLookupSystem().getCodeSystem().isEmpty())) {
      query = em.createNamedQuery("KMSpecialty.findAllDistinctScheme");
    } else {
      query = em.createNamedQuery("KMSpecialty.findAllDistinctSchemeByWildcard");
      query.setParameter(
          "terminologyScheme", refDetails.getLookupSystem().getCodeSystem().toUpperCase() + "%");
    }
    query.setFirstResult(startRec);
    query.setMaxResults(maxDisplay);
    List<String> foundList = (List<String>) query.getResultList();

    for (int r = 0; r < foundList.size(); r++) {
      ReferenceDataRefDataType aRefData = new ReferenceDataRefDataType();
      aRefData.setId(
          0); // TODO Need to pull the ID for each one of this type from ref_specialty_type
      // ..another call
      aRefData.setName(foundList.get(r));

      refColl.add(aRefData);
    }
    return refColl;
  }
  @Override
  public List<Productos> productosLike(String par, String id) {
    /*  String jpql = "SELECT EX.productos FROM Existencias EX "
    + " WHERE EX.bodegas.idBodega = '59' AND EX.productos.idProducto LIKE :par"
    + " OR EX.productos.nombre LIKE :par";*/
    String jpql =
        "SELECT PR FROM Productos PR where PR.idProducto LIKE :par OR PR.nombre LIKE :par";

    Query query = em.createQuery(jpql);

    String jpql1 =
        "select DISTINCT pro.IdProducto, pro.Nombre from bodegaVirtualMM vb inner join Productos pro on vb.IdProducto = pro.IdProducto and vb.IdVendedor = ? where   pro.IdProducto = ? or pro.Nombre like ? ";
    //   String jpql1 =   "select DISTINCT pro.IdProducto, pro.Nombre from bodegaVirtualMM vb inner
    // join Productos pro on vb.IdProducto = pro.IdProducto and vb.IdVendedor = ? order by
    // pro.Nombre";

    Query query2 = em.createNativeQuery(jpql1, Productos.class);
    query2.setParameter(1, id);
    query2.setParameter(2, par);
    query2.setParameter(3, "%" + par + "%");
    // query2.setParameter(1,  "%"+ par +"%");
    //  query2.setParameter("par", "%"+ par +"%");
    productosLikeList = query2.getResultList();
    return productosLikeList;

    /* String jpql =   "select us.UID, us.Nombre  as 'NombreUsuario' , pm.Nombre  as 'NombrePerfil', pm.Descripcion  as 'DescripcionPerfil' ,\n" +
    " am.Nombre  as NombreApp, am.Descripcion as 'DescripcionMovil' , am.Logo from Usuarios us inner join PerfilesMoviles pm \n" +
    "on us.IdPerfilMovil = pm.IdPerfilMovil inner join AppPorPerfiles ap on us.IdPerfilMovil = ap.IdPerfilMovil\n" +
    "inner join AppMoviles am on ap.IdAppMovil = am.IdAppMovil\n" +
    "where us.UID = :par" ;*/

  }
Example #9
0
  /**
   * 查询类别包含数量
   *
   * @param parentId
   * @param error
   * @return
   */
  public static List<v_news_types> queryTypeAndCount(long parentId, ErrorInfo error) {
    error.clear();

    List<v_news_types> types = new ArrayList<v_news_types>();
    StringBuffer sql = new StringBuffer("");
    sql.append(SQLTempletes.SELECT);
    sql.append(SQLTempletes.V_NEWS_TYPES);
    sql.append(" and parent_id = ? and status = true order by _order");

    try {
      // types = v_news_types.find("parent_id = ? and status = true order by _order",
      // parentId).fetch();
      EntityManager em = JPA.em();
      Query query = em.createNativeQuery(sql.toString(), v_news_types.class);
      query.setParameter(1, parentId);
      types = query.getResultList();

    } catch (Exception e) {
      e.printStackTrace();
      error.code = -1;
      error.msg = "查询类别失败";
      return null;
    }

    error.code = 0;

    return types;
  }
 public List<Permissao> listaPermissaoDepartamentoDisponivel(
     int idDepartamento, int idNivel, String descricaoPesquisa, int idCliente) {
   String queryFiltro = "";
   if (!descricaoPesquisa.equals("")) {
     queryFiltro = " AND UPPER(P.rotina.rotina) LIKE '%" + descricaoPesquisa.toUpperCase() + "%'";
   }
   try {
     Query query =
         getEntityManager()
             .createQuery(
                 " SELECT P FROM Permissao AS P WHERE P.id NOT IN ( SELECT PD.permissao.id FROM PermissaoDepartamento AS PD WHERE PD.departamento.id = "
                     + idDepartamento
                     + " AND PD.nivel.id = "
                     + idNivel
                     + " AND PD.cliente.id = "
                     + idCliente
                     + " ) "
                     + queryFiltro
                     + " ORDER BY P.modulo.descricao ASC, P.rotina.rotina ASC ");
     List list = query.getResultList();
     if (!list.isEmpty()) {
       return list;
     }
   } catch (Exception e) {
     return new ArrayList();
   }
   return new ArrayList();
 }
 public Permissao pesquisaPermissao(int idModulo, int idRotina, int idEvento, int idCliente) {
   try {
     Query query =
         getEntityManager()
             .createQuery(
                 "   SELECT P                                                "
                     + "   FROM Permissao AS P                                   "
                     + "  WHERE P.modulo.id      = :modulo                       "
                     + "    AND P.rotina.id      = :rotina                       "
                     + "    AND P.rotina.ativo   = true                          "
                     + "    AND P.segEvento.id   = :evento                       ");
     // + "    AND P.cliente.id     = :cliente                      ");
     query.setParameter("modulo", idModulo);
     query.setParameter("rotina", idRotina);
     query.setParameter("evento", idEvento);
     // query.setParameter("cliente", idCliente);
     List list = query.getResultList();
     if (!list.isEmpty() && list.size() == 1) {
       return (Permissao) query.getSingleResult();
     }
   } catch (Exception e) {
     return null;
   }
   return null;
 }
  public List pesquisaPermissaDisponivel(String ids) {
    String queryString;
    try {
      if (ids.length() == 0) {
        queryString =
            "SELECT P                                         "
                + "      FROM Permissao AS P                            "
                + "  ORDER BY P.modulo.descricao                        ";
      } else {
        queryString =
            "SELECT P                                         "
                + "      FROM Permissao AS P                            "
                + "     WHERE P.id NOT IN(                              "
                + "           SELECT PD.permissao.id                    "
                + "             FROM PermissaoDepartamento AS PD        "
                + "            WHERE PD.id IN("
                + ids
                + ")              "
                + "           )                                         "
                + "  ORDER BY P.modulo.descricao,                       "
                + "           P.rotina.rotina                           ";
      }

      Query query = getEntityManager().createQuery(queryString);
      List list = query.getResultList();
      if (!list.isEmpty()) {
        return list;
      }
    } catch (Exception e) {
    }
    return new ArrayList();
  }
Example #13
0
  /**
   * @param user1
   * @param user2
   * @return
   */
  @SuppressWarnings({"unused", "unchecked", "unchecked"})
  private List<ContentItem> getUserEditingInteractivity(User user1, User user2) {
    List<ContentItem> result = new LinkedList<ContentItem>();

    String s =
        " select ci from ContentItem ci join fetch ci.resource left outer join fetch ci.textContent tc "
            + " where ci.author.login =:user1 and tc.contentItem.author.login =:user2";

    javax.persistence.Query q = entityManager.createQuery(s);
    q.setParameter("user1", user1.getLogin());
    q.setParameter("user2", user2.getLogin());
    q.setHint("org.hibernate.cacheable", true);
    try {
      result = (List<ContentItem>) q.getResultList();
    } catch (PersistenceException ex) {
      ex.printStackTrace();
      log.warn("error while listing user: query failed");
    }

    if (result == null) {
      return Collections.EMPTY_LIST;
    } else {
      return result;
    }
  }
Example #14
0
  /**
   * @param user1
   * @param user2
   * @return
   */
  @SuppressWarnings({"unused", "unchecked", "unchecked"})
  private List<CommentActivity> getUserCommentInteractivity(User user1, User user2) {
    List<CommentActivity> result = new LinkedList<CommentActivity>();

    String s =
        "select a "
            + "from CommentActivity a inner join fetch a.comment left outer join a.contentItem as cia "
            + "where cia.author = :user1 and a.comment.author = :user2";

    Query q = entityManager.createQuery(s);
    q.setParameter("user1", user1);
    q.setParameter("user2", user2);
    q.setHint("org.hibernate.cacheable", true);
    try {
      result = (List<CommentActivity>) q.getResultList();
    } catch (PersistenceException ex) {
      ex.printStackTrace();
      log.warn("error while listing user: query failed");
    }

    if (result == null) {
      return Collections.EMPTY_LIST;
    } else {
      return result;
    }
  }
 @Override
 public List<Korisnik> sviKorisnici() {
   em.getEntityManagerFactory().getCache().evictAll();
   Query q = em.createNamedQuery("Korisnik.findAll");
   List<Korisnik> korisnici = q.getResultList();
   return korisnici;
 }
Example #16
0
  public List missingSurgeryReport(String days) {
    List resultList = null;

    Integer daysInteger = 0;
    Date limitDate = null;

    if (days != null && !days.equalsIgnoreCase("")) {
      limitDate = getLimitDate(Integer.valueOf(days));
    }

    String hql =
        "Select DISTINCT c from Client c "
            + "inner join c.colorectalCycles colorectalCycles "
            + "inner join colorectalCycles.rsdiFormPathologyReports pathologyReports "
            + "inner join pathologyReports.rsdiFormPathologyReport pathologyReport "
            + "where lower(pathologyReport.recommendedTestItem.code) like lower(:surgery) "
            + "and pathologyReport.reportCompletedDate <= :limitDate "
            + "and pathologyReport.rsdiFormClientSnapshot.clientId is not null ";

    /*+ "order by colorectalcancer.createDate DESC";*/

    Query q = getEntityManager().createQuery(hql);
    q.setParameter("surgery", "SURGERY");

    if (limitDate != null) {
      q.setParameter("limitDate", limitDate);
    }

    resultList = q.getResultList();

    return resultList;
  }
  @SuppressWarnings("unchecked")
  public List<Category> getCategories() {
    Query query =
        entityManager.createQuery("SELECT c FROM " + Category.class.getSimpleName() + " c");

    return (List<Category>) query.getResultList();
  }
Example #18
0
  public List needPathologyReport(String days) {
    List resultList = null;

    Integer daysInteger = 0;
    Date limitDate = null;

    if (days != null && !days.equalsIgnoreCase("")) {
      limitDate = getLimitDate(Integer.valueOf(days));
    }

    String hql =
        "Select DISTINCT c from Client c "
            + "left join c.colorectalCycles colorectalCycles "
            + "left join colorectalCycles.rsdiFormColorectalCancers colorectalCancers "
            + "left join colorectalCancers.rsdiFormColorectalCancer colorectalCancer "
            + "where lower(colorectalCancer.performedBiopsyItem.code) like lower(:yes) "
            + "and colorectalCancer.performedDate >= :limitDate "
            + "and colorectalcancer.rsdiFormClientSnapshot.clientId is not null ";

    /*+ "order by colorectalcancer.createDate DESC";*/

    Query q = getEntityManager().createQuery(hql);
    q.setParameter("surgery", "SURGERY");

    if (limitDate != null) {
      q.setParameter("limitDate", limitDate);
    }

    resultList = q.getResultList();

    return resultList;
  }
 @TransactionAttribute(REQUIRES_NEW)
 public int clearAllIndexTimes() {
   Query clearIndexTimes =
       em.createQuery("UPDATE DvObject o SET o.indexTime = NULL, o.permissionIndexTime = NULL");
   int numRowsUpdated = clearIndexTimes.executeUpdate();
   return numRowsUpdated;
 }
Example #20
0
 /**
  * 通过物资编码查询物资类别信息
  *
  * @param materialCode 物资编码 物资编码
  * @return
  */
 public ArrayList FindmaterialTypeBymaterialCode(String materialCode) {
   ArrayList list = new ArrayList(); // 创建list
   Query q =
       em.createQuery(
           "select p from wzMaterialRecord p where p.materialCode =:materialCode"); // 建立带有参数的查询
   q.setParameter("materialCode", materialCode); // 注入查询参数
   if (!q.getResultList().isEmpty()) {
     wzMaterialRecord mr = (wzMaterialRecord) q.getSingleResult(); // 返回单条结果
     if (mr.getMaterialOneType() != null && mr.getMaterialOneType().getOneType() != 0) {
       list.add(mr.getMaterialOneType().getOneType());
     } else {
       list.add("");
     }
     if (mr.getMaterialOneType() != null && mr.getMaterialOneType().getOneTypeName() != null) {
       list.add(mr.getMaterialOneType().getOneTypeName());
     } else {
       list.add("");
     }
     if (mr.getMaterialTwoType() != null && mr.getMaterialTwoType().getTwoType() != 0) {
       list.add(mr.getMaterialTwoType().getTwoType());
     } else {
       list.add("");
     }
     if (mr.getMaterialTwoType() != null && mr.getMaterialTwoType().getTwoTypeName() != null) {
       list.add(mr.getMaterialTwoType().getTwoTypeName());
     } else {
       list.add("");
     }
   }
   return list; // 返回list
 }
  @Override
  /** {@Inheritdoc} */
  public List<RESTEndpoint> getRestEndpoints(URI anyURI, CSARID csarId) {
    this.init();
    ArrayList<RESTEndpoint> results = new ArrayList<RESTEndpoint>();

    /**
     * Create Query to retrieve RESTEndpoints identified by a URI and thorID
     *
     * @see RESTEndpoint#getEndpointForPath
     */
    Query getRestEndpointsQuery = this.em.createNamedQuery(RESTEndpoint.getEndpointForPath);

    // Set Parameters
    getRestEndpointsQuery.setParameter("path", anyURI.getPath());
    getRestEndpointsQuery.setParameter("csarId", csarId);

    // Get Query-Results and add them to the result list
    @SuppressWarnings("unchecked")
    // Result can only be a RESTEndpoint
    List<RESTEndpoint> queryResults = getRestEndpointsQuery.getResultList();
    for (RESTEndpoint endpoint : queryResults) {
      results.add(endpoint);
    }
    return results;
  }
Example #22
0
  private void initDialog() {
    initPhase = true;
    cmbDaysWeeks.setModel(
        new DefaultComboBoxModel(
            new String[] {SYSTools.xx("misc.msg.Days"), SYSTools.xx("misc.msg.weeks")}));
    cbWeightControlled.setText(
        SYSTools.xx("opde.medication.medproduct.wizard.subtext.weightControlled"));
    cbWeightControlled.setSelected(tradeForm.isWeightControlled());
    cbExpiresAfterOpened.setText(SYSTools.xx("tradeform.subtext.expiresAfterOpenedIn"));
    cbExpiresAfterOpened.setSelected(tradeForm.getDaysToExpireAfterOpened() != null);
    txtExpiresIn.setEnabled(cbExpiresAfterOpened.isSelected());
    cmbDaysWeeks.setEnabled(cbExpiresAfterOpened.isSelected());
    Pair<Integer, Integer> pair = TradeFormTools.getExpiresIn(tradeForm);
    if (pair != null) {
      txtExpiresIn.setText(
          pair.getFirst() > 0 ? pair.getFirst().toString() : pair.getSecond().toString());
      cmbDaysWeeks.setSelectedIndex(pair.getFirst() > 0 ? 0 : 1);
    }

    EntityManager em = OPDE.createEM();
    Query query = em.createQuery("SELECT m FROM DosageForm m ORDER BY m.preparation, m.usageText");
    cmbForm.setModel(new DefaultComboBoxModel(query.getResultList().toArray(new DosageForm[] {})));
    cmbForm.setRenderer(DosageFormTools.getRenderer(0));
    em.close();

    cmbForm.setSelectedItem(tradeForm.getDosageForm());
    txtZusatz.setText(SYSTools.catchNull(tradeForm.getSubtext()));

    btnAdd.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, "opde.medication"));
    btnEdit.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, "opde.medication"));
    initPhase = false;
  }
  @Override
  public void printPlanEndpoints() {
    this.init();
    this.em.getTransaction().begin();
    List<WSDLEndpoint> endpoints = null;
    Query queryWSDLEndpoint = this.em.createQuery("SELECT e FROM WSDLEndpoint e");

    endpoints = queryWSDLEndpoint.getResultList();
    this.em.getTransaction().commit();

    StringBuilder builder = new StringBuilder();
    String ls = System.getProperty("line.separator");
    builder.append(
        "debug output for stored endpoints of management plans, flags: csarid, planid, ianame, porttype "
            + ls);
    for (WSDLEndpoint endpoint : endpoints) {
      builder.append(
          "endpoint: "
              + endpoint.getCSARId()
              + " "
              + endpoint.getPlanId()
              + " "
              + endpoint.getIaName()
              + " "
              + endpoint.getPortType()
              + ls);
    }
    CoreInternalEndpointServiceImpl.LOG.debug(builder.toString());
  }
  public TblMaterial getBasicInfo(String noParte) {
    Query query =
        em.createQuery(
            "SELECT  c.idtblMaterial,c.noParte,c.nombre,c.descripcion,c.stock,c.costo,c.imagen, c.idArea.idArea, c.idTipomaterial.idTipomaterial,c.subFamiliasidsubFam.idsubFam, c.idArea.descripcion, c.idTipomaterial.descripcion, c.subFamiliasidsubFam.nombre  FROM TblMaterial c WHERE c.noParte = :noParte");
    query.setParameter("noParte", noParte);

    Object[] object = (Object[]) query.getSingleResult();
    TblMaterial temp = new TblMaterial();
    temp.setIdtblMaterial((Integer) object[0]);
    temp.setNoParte((String) (object[1]));
    temp.setNombre((String) (object[2]));
    temp.setDescripcion((String) (object[3]));
    temp.setStock((Integer) (object[4]));
    temp.setCosto((Long) (object[5]));
    temp.setImagen((String) (object[6]));

    TblArea area = new TblArea((Integer) (object[7]));
    area.setDescripcion((String) object[10]);
    temp.setIdArea(area);

    TblTipomaterial tipo = new TblTipomaterial((Integer) (object[8]));
    tipo.setDescripcion((String) object[11]);
    temp.setIdTipomaterial(tipo);

    Subfamilias sub = new Subfamilias((Integer) (object[9]));
    sub.setNombre((String) object[12]);
    temp.setSubFamiliasidsubFam(sub);

    return temp;
  }
 public List<BookLending> showAllLendings(Customer customer) {
   Query query = em.createNamedQuery("findLendingByCustomer");
   query.setParameter("customer", customer);
   List<BookLending> bookLendings = query.getResultList();
   if (bookLendings.isEmpty()) return null;
   return bookLendings;
 }
Example #26
0
  public int count(List<Filtro> filtros) {
    javax.persistence.criteria.CriteriaQuery cq =
        getEntityManager().getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<BaseEntity> rt = cq.from(entityClass);
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();

    if (filtros != null) {
      ArrayList<Predicate> predicatesList = new ArrayList<>();
      for (Filtro filtro : filtros) {
        switch (filtro.getTipoFiltro()) {
          case Equals:
            predicatesList.add(builder.equal(rt.get(filtro.getDescricao()), filtro.getValor()));
            break;
          case LessEqual:
            Path<Date> date = rt.get(filtro.getDescricao());
            predicatesList.add(builder.lessThanOrEqualTo(date, ((Date) filtro.getValor())));
            break;
          case GreaterEqual:
            Path<Date> date2 = rt.get(filtro.getDescricao());
            predicatesList.add(builder.greaterThanOrEqualTo(date2, ((Date) filtro.getValor())));
            break;
          default:
            predicatesList.add(builder.equal(rt.get(filtro.getDescricao()), filtro.getValor()));
            break;
        }
      }
      cq.where(predicatesList.<Predicate>toArray(new Predicate[predicatesList.size()]));
    }

    cq.select(builder.count(rt));
    javax.persistence.Query q = getEntityManager().createQuery(cq);

    return ((Long) q.getSingleResult()).intValue();
  }
 public int getVoteCount() {
   CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
   Root<Vote> rt = cq.from(Vote.class);
   cq.select(em.getCriteriaBuilder().count(rt));
   Query q = em.createQuery(cq);
   return ((Long) q.getSingleResult()).intValue();
 }
Example #28
0
 // User defined finders/Buscadores definidos por el usuario
 public static Size findById(int id) throws javax.ejb.ObjectNotFoundException {
   if (XavaPreferences.getInstance().isJPAPersistence()) {
     javax.persistence.Query query =
         org.openxava.jpa.XPersistence.getManager()
             .createQuery("from Size as o where o.id = :arg0");
     query.setParameter("arg0", new Integer(id));
     try {
       return (Size) query.getSingleResult();
     } catch (Exception ex) {
       // In this way in order to work with Java pre 5
       if (ex.getClass().getName().equals("javax.persistence.NoResultException")) {
         throw new javax.ejb.ObjectNotFoundException(
             XavaResources.getString("object_not_found", "Size"));
       } else {
         ex.printStackTrace();
         throw new RuntimeException(ex.getMessage());
       }
     }
   } else {
     org.hibernate.Query query =
         org.openxava.hibernate.XHibernate.getSession()
             .createQuery("from Size as o where o.id = :arg0");
     query.setParameter("arg0", new Integer(id));
     Size r = (Size) query.uniqueResult();
     if (r == null) {
       throw new javax.ejb.ObjectNotFoundException(
           XavaResources.getString("object_not_found", "Size"));
     }
     return r;
   }
 }
  /**
   * Find all News entities.
   *
   * @param rowStartIdxAndCount Optional int varargs. rowStartIdxAndCount[0] specifies the the row
   *     index in the query result-set to begin collecting the results. rowStartIdxAndCount[1]
   *     specifies the the maximum count of results to return.
   * @return List<News> all News entities
   */
  @SuppressWarnings("unchecked")
  public List<News> findAll(final int... rowStartIdxAndCount) {
    LogUtil.log("finding all News instances", Level.INFO, null);
    try {
      final String queryString = "select model from News model";
      Query query = entityManager.createQuery(queryString);
      if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
        int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
        if (rowStartIdx > 0) {
          query.setFirstResult(rowStartIdx);
        }

        if (rowStartIdxAndCount.length > 1) {
          int rowCount = Math.max(0, rowStartIdxAndCount[1]);
          if (rowCount > 0) {
            query.setMaxResults(rowCount);
          }
        }
      }
      return query.getResultList();
    } catch (RuntimeException re) {
      LogUtil.log("find all failed", Level.SEVERE, re);
      throw re;
    }
  }
Example #30
0
 @SuppressWarnings("unchecked")
 @Override
 public List<Banda> buscarTodos() {
   String jpql = "SELECT x FROM Banda x";
   Query query = em.createQuery(jpql);
   return query.getResultList();
 }