Ejemplo n.º 1
1
  @Override
  public Object bind(
      RootParamNode rootParamNode,
      String name,
      Class clazz,
      java.lang.reflect.Type type,
      Annotation[] annotations) {
    // TODO need to be more generic in order to work with JPASupport
    if (clazz.isAnnotationPresent(Entity.class)) {

      ParamNode paramNode = rootParamNode.getChild(name, true);

      String[] keyNames = new JPAModelLoader(clazz).keyNames();
      ParamNode[] ids = new ParamNode[keyNames.length];
      // Collect the matching ids
      int i = 0;
      for (String keyName : keyNames) {
        ids[i++] = paramNode.getChild(keyName, true);
      }
      if (ids != null && ids.length > 0) {
        try {
          EntityManager em = JPABase.getJPAConfig(clazz).getJPAContext().em();
          StringBuilder q =
              new StringBuilder().append("from ").append(clazz.getName()).append(" o where");
          int keyIdx = 1;
          for (String keyName : keyNames) {
            q.append(" o.").append(keyName).append(" = ?").append(keyIdx++).append(" and ");
          }
          if (q.length() > 4) {
            q = q.delete(q.length() - 4, q.length());
          }
          Query query = em.createQuery(q.toString());
          // The primary key can be a composite.
          Class[] pk = new JPAModelLoader(clazz).keyTypes();
          int j = 0;
          for (ParamNode id : ids) {
            if (id.getValues() == null
                || id.getValues().length == 0
                || id.getFirstValue(null) == null
                || id.getFirstValue(null).trim().length() <= 0) {
              // We have no ids, it is a new entity
              return GenericModel.create(rootParamNode, name, clazz, annotations);
            }
            query.setParameter(
                j + 1,
                Binder.directBind(
                    id.getOriginalKey(), annotations, id.getValues()[0], pk[j++], null));
          }
          Object o = query.getSingleResult();
          return GenericModel.edit(rootParamNode, name, o, annotations);
        } catch (NoResultException e) {
          // ok
        } catch (Exception e) {
          throw new UnexpectedException(e);
        }
      }
      return GenericModel.create(rootParamNode, name, clazz, annotations);
    }
    return null;
  }
  /**
   * test for issue 635: NullPointerException occuring for Object typed version fields. Employee has
   * a write lock (version) field of type Integer The NullPointerException is thrown when comparing
   * versions in ObjectChangeSet#compareWriteLockValues
   */
  public void testCreateEmployeeWithFlush() {
    EntityManager em = createEntityManager("fieldaccess");
    Project project1, project2;
    Employee employee;

    try {
      beginTransaction(em);
      employee = ModelExamples.employeeExample1();
      em.persist(employee);

      // first flush: Employee is written to the database
      Query query = em.createNamedQuery("findFieldAccessProjectByName");
      query.setParameter("name", "Farmer effecency evaluations");
      project1 = (Project) query.getSingleResult();
      employee.getProjects().add(project1);

      // second flush: Employee is modified, but
      // no update to EMPLOYEE table; only join table entry is written
      query = em.createNamedQuery("findFieldAccessProjectByName");
      query.setParameter("name", "Feline Demographics Assesment");
      project2 = (Project) query.getSingleResult();
      employee.getProjects().add(project2);

      // third flush: Employee is modified, but
      // no update to EMPLOYEE table; only join table entry is written
      // A NullPointerException in ObjectChangeSet#compareWriteLockValues
      commitTransaction(em);
    } catch (RuntimeException e) {
      if (isTransactionActive(em)) {
        rollbackTransaction(em);
      }
      closeEntityManager(em);
      throw e;
    }
  }
Ejemplo n.º 3
0
  //    //Returns all the electives proposed by students and teachears!
  //    @Override
  //    public Collection<ElectiveDTO> getProposedElectives() {
  //        ArrayList< ElectiveDTO> electiveDTOs = new ArrayList<>();
  //        Query query = entityManager.createNamedQuery("Elective.findAll");
  //        List<Elective> electives = query.getResultList();
  //        for (Elective e : electives) {
  //            if (e.getProposed().equals("0")) {
  //                electiveDTOs.add(new ElectiveDTO(e.getElectiveId(), e.getTitle(),
  // e.getDescription(), e.getCreationDate(), e.getProposed()));
  //            }
  //        }
  //        return electiveDTOs;
  //    }
  // Returns electives that has been approved by the head of program to go for the first round
  @Override
  public Collection<ElectiveFirstDTO> getFirstRndElectives() {

    ArrayList<ElectiveFirstDTO> electiveDTOs = new ArrayList<>();
    Query query = entityManager.createNamedQuery("Elective.findByProposed");
    Query q1, q2;
    query.setParameter("proposed", "1");
    List<Elective> electives = query.getResultList();

    int firstPriorityCount;
    int secondPriorityCount;

    for (Elective e : electives) {
      if (e.getPool() == null) {
        q1 = entityManager.createNamedQuery("FirstRoundVote.count_priority1");
        q1.setParameter("elective", e);
        firstPriorityCount = Integer.parseInt(q1.getSingleResult().toString());

        q2 = entityManager.createNamedQuery("FirstRoundVote.count_priority2");
        q2.setParameter("elective", e);
        secondPriorityCount = Integer.parseInt(q2.getSingleResult().toString());
        electiveDTOs.add(
            new ElectiveFirstDTO(
                e.getElectiveId(),
                e.getTitle(),
                e.getDescription(),
                e.getCreationDate(),
                e.getProposed(),
                firstPriorityCount,
                secondPriorityCount));
      }
    }
    return electiveDTOs;
  }
  /**
   * Get the number of messages (activity and comment) posted on a specific day.
   *
   * @param inDay the date to look for stats
   * @return the number of activities and comments posted on the input day
   */
  @Override
  public Long execute(final Date inDay) {
    Long activityCount, commentCount;
    Date startOfDay, endOfDay;
    Query q;

    startOfDay = DateDayExtractor.getStartOfDay(inDay);
    endOfDay = DateDayExtractor.getEndOfDay(inDay);

    // get the activity count
    q =
        getEntityManager()
            .createQuery(
                "SELECT COUNT(*) FROM Activity WHERE (appType = null OR appType != :plugin) AND "
                    + "postedTime >= :startDate AND postedTime <= :endDate")
            .setParameter("startDate", startOfDay)
            .setParameter("endDate", endOfDay)
            .setParameter("plugin", EntityType.PLUGIN);
    activityCount = (Long) q.getSingleResult();

    // get the comment count
    q =
        getEntityManager()
            .createQuery(
                "SELECT COUNT(*) FROM Comment WHERE timeSent >= :startDate AND timeSent <= :endDate")
            .setParameter("startDate", startOfDay)
            .setParameter("endDate", endOfDay);
    commentCount = (Long) q.getSingleResult();

    return activityCount + commentCount;
  }
Ejemplo n.º 5
0
  /** Tests creation of users. */
  @Test
  public void testCreation() {

    Query countQuery = em.createQuery("select count(u) from User u");
    Long before = (Long) countQuery.getSingleResult();

    flushTestUsers();

    assertEquals(before + 3, countQuery.getSingleResult());
  }
Ejemplo n.º 6
0
  private void storeValue(
      Integer projectId,
      Integer elementId,
      Integer iterationId,
      Amendment amendment,
      List<HistoryToken> historyTokens) {
    // The value of the current flexible element must be saved.
    final Query maxDateQuery;
    if (iterationId == null) {
      maxDateQuery =
          em().createQuery(
                  "SELECT MAX(h.date) FROM HistoryToken h WHERE h.elementId = :elementId AND h.projectId = :projectId");
      maxDateQuery.setParameter("projectId", projectId);
      maxDateQuery.setParameter("elementId", elementId);
    } else {
      maxDateQuery =
          em().createQuery(
                  "SELECT MAX(h.date) FROM HistoryToken h WHERE h.elementId = :elementId AND h.projectId = :projectId AND h.layoutGroupIterationId = :iterationId");
      maxDateQuery.setParameter("projectId", projectId);
      maxDateQuery.setParameter("elementId", elementId);
      maxDateQuery.setParameter("iterationId", iterationId);
    }

    try {
      final Date maxDate = (Date) maxDateQuery.getSingleResult();

      final Query query;

      if (iterationId == null) {
        query =
            em().createQuery(
                    "SELECT h FROM HistoryToken h WHERE h.elementId = :elementId AND h.projectId = :projectId AND h.date = :maxDate");
        query.setParameter("projectId", projectId);
        query.setParameter("elementId", elementId);
        query.setParameter("maxDate", maxDate);
      } else {
        query =
            em().createQuery(
                    "SELECT h FROM HistoryToken h WHERE h.elementId = :elementId AND h.projectId = :projectId AND h.date = :maxDate AND h.layoutGroupIterationId = :iterationId");
        query.setParameter("projectId", projectId);
        query.setParameter("elementId", elementId);
        query.setParameter("maxDate", maxDate);
        query.setParameter("iterationId", iterationId);
      }

      final HistoryToken token = (HistoryToken) query.getSingleResult();
      token.setCoreVersion(amendment);
      em().merge(token);

      historyTokens.add(token);

    } catch (NoResultException e) {
      // There is no history token for the given element. No action.
    }
  }
Ejemplo n.º 7
0
  @Override
  public PrivateUser login(String username, String password) {
    Query q = em.createNamedQuery("User.login", User.class);
    q.setParameter("username", username);
    q.setParameter("password", password);
    try {
      if (q.getSingleResult() != null) {
        PrivateUser pu = (PrivateUser) q.getSingleResult();
        return pu;
      }
    } catch (Exception ex) {

    }
    return null;
  }
 @Override
 public String getLastUpdateDate() {
   String candidateAttendanceDate = "";
   String sqlForMaxId = "SELECT max(cands_exam_attendance_id) FROM CANDS_EXAM_ATTENDANCE";
   String sqlForMaxRecord =
       "SELECT to_char(create_date,'dd/MM/yyyy HH24:MI') FROM CANDS_EXAM_ATTENDANCE WHERE cands_exam_attendance_id=:id";
   Query queryForId = entityManager.createNativeQuery(sqlForMaxId);
   Query queryForRecord = entityManager.createNativeQuery(sqlForMaxRecord);
   BigDecimal maxId = (BigDecimal) queryForId.getSingleResult();
   if (maxId != null) {
     queryForRecord.setParameter("id", maxId.toBigInteger().longValue());
     candidateAttendanceDate = (String) queryForRecord.getSingleResult();
   }
   return candidateAttendanceDate;
 }
 public Resource get(ResourceType type, Object name) {
   EntityManager em = ResourceUtils.getEntityManager();
   em.getTransaction().begin();
   QueryGenerator generator;
   Query q;
   switch (type) {
     case WORKFLOW_DATA:
       generator = new QueryGenerator(WORKFLOW_DATA);
       //                generator.setParameter(WorkflowDataConstants.EXPERIMENT_ID, experimentID);
       generator.setParameter(WorkflowDataConstants.WORKFLOW_INSTANCE_ID, name);
       q = generator.selectQuery(em);
       Workflow_Data eworkflowData = (Workflow_Data) q.getSingleResult();
       WorkflowDataResource workflowDataResource =
           (WorkflowDataResource) Utils.getResource(ResourceType.WORKFLOW_DATA, eworkflowData);
       em.getTransaction().commit();
       em.close();
       return workflowDataResource;
     case EXPERIMENT_METADATA:
       generator = new QueryGenerator(EXPERIMENT_METADATA);
       generator.setParameter(ExperimentDataConstants.EXPERIMENT_ID, name);
       q = generator.selectQuery(em);
       Experiment_Metadata expMetadata = (Experiment_Metadata) q.getSingleResult();
       ExperimentMetadataResource experimentMetadataResource =
           (ExperimentMetadataResource)
               Utils.getResource(ResourceType.EXPERIMENT_METADATA, expMetadata);
       em.getTransaction().commit();
       em.close();
       return experimentMetadataResource;
     case GFAC_JOB_DATA:
       generator = new QueryGenerator(GFAC_JOB_DATA);
       generator.setParameter(GFacJobDataConstants.LOCAL_JOB_ID, name);
       q = generator.selectQuery(em);
       GFac_Job_Data gFacJobData = (GFac_Job_Data) q.getSingleResult();
       GFacJobDataResource gFacJobDataResource =
           (GFacJobDataResource) Utils.getResource(ResourceType.GFAC_JOB_DATA, gFacJobData);
       em.getTransaction().commit();
       em.close();
       return gFacJobDataResource;
     default:
       em.getTransaction().commit();
       em.close();
       logger.error(
           "Unsupported resource type for experiment data resource... ",
           new UnsupportedOperationException());
       throw new IllegalArgumentException(
           "Unsupported resource type for experiment data resource.");
   }
 }
 /** Devuelve unaDeuda por ID incluido los borrados */
 public Deuda getDeudaBD(Long id) {
   Deuda resultado;
   Query traerDeuda =
       this.entityManager.createQuery("SELECT auxCD FROM Deuda auxCD WHERE auxCD.idDeuda = " + id);
   resultado = (Deuda) traerDeuda.getSingleResult();
   return resultado;
 }
Ejemplo n.º 11
0
  @Override
  public void removeClaimFromApplication(Application application, RequestClaim claim) {
    ApplicationEntity applicationEntity = null;
    if (application.getId() != 0) {
      applicationEntity = em.find(ApplicationEntity.class, application.getId());
    } else {
      Query query = null;
      query = em.createQuery("select a from Application a where a.realm=:realm");
      query.setParameter("realm", application.getRealm());

      applicationEntity = (ApplicationEntity) query.getSingleResult();
    }

    ApplicationClaimEntity foundEntity = null;
    for (ApplicationClaimEntity acm : applicationEntity.getRequestedClaims()) {
      if (claim.getClaimType().toString().equals(acm.getClaim().getClaimType())) {
        foundEntity = acm;
        break;
      }
    }
    if (foundEntity == null) {
      throw new EntityNotFoundException("ApplicationClaimEntity not found");
    }

    applicationEntity.getRequestedClaims().remove(foundEntity);
  }
Ejemplo n.º 12
0
  public Page<Object[]> getCustomerService(int pageNo, int pageSize, Date minDate, Date maxDate) {
    String hql =
        "select count(cs.serviceType) from CustomerService cs "
            + "  where cs.customer is not null And cs.serviceType is not null "
            + "  and cs.createDate between ? and ?";

    Query query = entityManager.createQuery(hql);
    query.setParameter(1, minDate);
    query.setParameter(2, maxDate);
    long total = (long) query.getSingleResult();

    hql =
        "select cs.serviceType , count(cs.serviceType) from CustomerService cs "
            + "where cs.customer is not null and cs.serviceType is not null and cs.createDate between ? and ? "
            + " group by cs.serviceType";

    query = entityManager.createQuery(hql);
    query.setParameter(1, minDate);
    query.setParameter(2, maxDate);

    query.setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize);
    List<Object[]> content = query.getResultList();

    PageRequest pageable = new PageRequest(pageNo - 1, pageSize);

    PageImpl<Object[]> page = new PageImpl<Object[]>(content, pageable, total);

    return page;
  }
  @Override
  public Boolean demandeOwner(String restaurantId, Integer OwnerId) {

    Restaurant restaurant =
        factoryServiceLocal.getRestaurantEjb().findById(restaurantId, Restaurant.class);
    Owner owner = factoryServiceLocal.getOwnerEjb().findById(OwnerId, Owner.class);

    if (restaurant == null || owner == null || restaurant instanceof Complaint) {
      return false;
    }

    String jpql = "select e from ValidateOwnerRestaurant e where e.restaurant.id =:param";
    Query query = entityManager.createQuery(jpql);
    query.setParameter("param", restaurantId);
    ValidateOwnerRestaurant ownerRestaurant = null;
    try {
      ownerRestaurant = (ValidateOwnerRestaurant) query.getSingleResult();
    } catch (Exception ee) {
    }
    String code = "";
    if (ownerRestaurant == null) {
      code = SendMail.generateCode();
      factoryServiceLocal
          .getValidateOwnerRestaurantEjb()
          .add(new ValidateOwnerRestaurant(code, new Date(), null, restaurant, owner));
    } else code = ownerRestaurant.getCode();

    SendMail.sendMail(restaurant.getEmail(), code);

    return true;
  }
  /**
   * Y a t'il d'autres facture a exporter pour le même payeur ?
   *
   * @param moveLineList : une liste de ligne d'écriture de facture
   * @param psl
   * @return
   */
  public boolean hasOtherInvoice(List<MoveLine> moveLineList, MoveLine moveLine) {

    Partner partner = moveLine.getPartner();

    Query q =
        JPA.em()
            .createQuery(
                "select count(*) FROM MoveLine as self WHERE self IN ?1 AND self.partner = ?2 ");
    q.setParameter(1, moveLineList);
    q.setParameter(2, partner);

    if ((long) q.getSingleResult() > 1) {
      log.debug(
          "Recherche d'une autre facture à prélever (autre que l'écriture {}) pour le tiers {} : OUI",
          moveLine.getName(),
          partner.getFullName());
      return true;
    }

    log.debug(
        "Recherche d'une autre facture à prélever (autre que l'écriture {}) pour le tiers {} : NON",
        moveLine.getName(),
        partner.getFullName());

    return false;
  }
 public Estado encontrar(int id) {
   EntityManager em = FactoryDAO.em;
   Query q = em.createQuery("FROM misClases.Estado u WHERE u.id = ?1");
   q.setParameter(1, id);
   Estado user = (Estado) q.getSingleResult();
   return user;
 }
Ejemplo n.º 16
0
 /**
  * 描述:更近sc统计相关信息条数 <br>
  * 创建时间:2013-5-11 下午11:51:02
  *
  * @author liyang
  * @param lockMode
  * @param cacheName
  * @param sc
  * @return
  */
 public Object statBySearchCriterion(
     final LockModeType lockMode, final ConstantsEnum.EHCACHE cacheName, SearchCriterion sc) {
   if (sc == null) {
     sc = new SearchCriterion();
   }
   Map<String, Object> map = sc.getFilterMap();
   Query query = entityManager.createQuery("select count(*) " + this.getJPQL(sc));
   if (map != null && !map.isEmpty()) {
     for (String str : map.keySet()) {
       if (str.split("\\.").length > 1) {
         query.setParameter(str.split("\\.")[1], map.get(str));
       } else {
         query.setParameter(str, map.get(str));
       }
     }
   }
   map = sc.getFilterValue();
   if (map != null && !map.isEmpty()) {
     for (String str : map.keySet()) {
       if (str.split("\\.").length > 1) {
         query.setParameter(str.split("\\.")[1], map.get(str));
       } else {
         query.setParameter(str, map.get(str));
       }
     }
   }
   if (lockMode != null) {
     query.setLockMode(lockMode);
   }
   if (cacheName != null) {
     query.setHint("org.hibernate.cacheable", true);
     query.setHint("org.hibernate.cacheRegion", cacheName.getStr());
   }
   return query.getSingleResult();
 }
Ejemplo n.º 17
0
  public CuentaCteTitularMutual findCuentaCteTitularMutual(TitularMutual tm) {
    EntityManager em = createEntityManager();
    CuentaCteTitularMutual cctm = null;
    try {

      em.getTransaction().begin();

      String consulta =
          "SELECT o FROM "
              + CuentaCteTitularMutual.class.getSimpleName()
              + " o"
              + " WHERE o.titulares.cuil='"
              + tm.getTitular().getCuil()
              + "'"
              + " ORDER BY o.periodo DESC";
      Query q = em.createQuery(consulta);
      q.setMaxResults(1);
      cctm = (CuentaCteTitularMutual) q.getSingleResult();
    } catch (NoResultException e) {

    } finally {
      em.getTransaction().rollback();
    }
    return cctm;
  }
 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();
 }
 // <editor-fold defaultstate="collapsed" desc="Cuotas">
 public Cuota getCuotaBD(Long id) {
   Cuota resultado;
   Query traerCuota =
       this.entityManager.createQuery("SELECT auxCD FROM Cuota auxCD WHERE auxCD.idCuota = " + id);
   resultado = (Cuota) traerCuota.getSingleResult();
   return resultado;
 }
  @Override
  public Long getTotalContentDownloads(
      Company company, Date eventDate, Campaign campaign, Device device) {
    String query =
        "SELECT COUNT(b.id) FROM BluetoothSend b WHERE b.sendStatus = ?1 AND b.eventDate BETWEEN ?2 AND ?3 AND b.company = ?4 ";
    int paramCount = 4;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }

    Query q = em.createQuery(query);
    q.setParameter(1, BluetoothSend.STATUS_SENT);
    q.setParameter(2, eventDate);
    q.setParameter(3, DateUtil.getEndOfDay(eventDate));
    q.setParameter(4, company);

    for (Map.Entry<Integer, Object> entry : params.entrySet()) {
      Integer paramId = entry.getKey();
      Object object = entry.getValue();
      q.setParameter(paramId, object);
    }

    Long countResult = (Long) q.getSingleResult();
    return countResult;
  }
Ejemplo n.º 21
0
  public int findUserVisitsNo(Integer userId) {
    Query q = em.createNamedQuery("findUserVisitsNo");
    q.setParameter("userId", userId);

    int result = (int) q.getSingleResult();
    return result;
  }
  @Override
  public Long getUniqueDevicesSupportingBluetooth(
      Company company, Date eventDate, Campaign campaign, Device device) {
    String query =
        "SELECT COUNT(DISTINCT b.macAddress) FROM BluetoothSend b WHERE b.eventDate BETWEEN ?1 AND ?2 AND b.company = ?3 AND b.sendStatus in (1, 2, 3, 4, 5, 7) ";
    int paramCount = 3;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }
    Query q = em.createQuery(query);

    q.setParameter(1, eventDate);
    q.setParameter(2, DateUtil.getEndOfDay(eventDate));
    q.setParameter(3, company);

    for (Map.Entry<Integer, Object> entry : params.entrySet()) {
      Integer paramId = entry.getKey();
      Object object = entry.getValue();
      q.setParameter(paramId, object);
    }

    Long countResult = (Long) q.getSingleResult();
    return countResult;
  }
  @Override
  public Long getUniqueDevicesAcceptingPush(
      Company company, Date eventDate, Campaign campaign, Device device) {
    String query =
        "SELECT COUNT(DISTINCT b.macAddress) FROM BluetoothSend b WHERE (b.acceptStatus = ?1 OR b.sendStatus = ?2) AND b.eventDate BETWEEN ?3 AND ?4 AND b.company = ?5 ";
    int paramCount = 5;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }
    Query q = em.createQuery(query);

    q.setParameter(1, 1);
    q.setParameter(2, BluetoothSend.STATUS_ACCEPTED);
    q.setParameter(3, eventDate);
    q.setParameter(4, DateUtil.getEndOfDay(eventDate));
    q.setParameter(5, company);

    for (Map.Entry<Integer, Object> entry : params.entrySet()) {
      Integer paramId = entry.getKey();
      Object object = entry.getValue();
      q.setParameter(paramId, object);
    }

    Long countResult = (Long) q.getSingleResult();
    return countResult;
  }
Ejemplo n.º 24
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;
   }
 }
 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();
 }
Ejemplo n.º 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();
  }
Ejemplo n.º 27
0
  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;
  }
Ejemplo n.º 28
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
 }
 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;
 }
Ejemplo n.º 30
-1
  public TitularMutual findBy(Titulares titulares, Boolean baja) {
    EntityManager em = createEntityManager();
    TitularMutual tm = null;
    try {

      em.getTransaction().begin();
      String query;
      if (baja == null) {
        query = "";
      } else if (baja) {
        query = " AND o.fechaBaja IS NOT NULL";
      } else {
        query = " AND o.fechaBaja IS NULL";
      }
      String consulta =
          "SELECT o FROM TitularMutual o" + " WHERE o.titular.id=" + titulares.getId() + query;
      Query q = em.createQuery(consulta);
      tm = (TitularMutual) q.getSingleResult();
    } catch (NoResultException e) {

    } finally {
      em.getTransaction().rollback();
    }
    return tm;
  }