Java Code Examples for javax.persistence.Query.setParameter()

The following are Jave code examples for showing how to use setParameter() of the javax.persistence.Query class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: oscm   File: SubscriptionDao.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
List<Subscription> getSubscriptionsForOrg(PlatformUser user,
        Set<SubscriptionStatus> states,
        org.oscm.paginator.Pagination pagination, String queryString,
        Long... keys) {

    Set<String> statesAsString = getSubscriptionStatesAsString(states);
    Query query = dataManager.createNativeQuery(queryString,
            Subscription.class);
    try {
        query.setParameter("locale", user.getLocale());
        query.setParameter("objecttype",
                LocalizedObjectTypes.PRODUCT_MARKETING_NAME.name());
    } catch (IllegalArgumentException exc) {
        logger.logDebug("Parameters are not found in the query. Not an error, just sorting is not applied.");
    }
    query.setParameter("organization",
            Long.valueOf(user.getOrganization().getKey()));
    query.setParameter("states", statesAsString);

    setPaginationParameters(pagination, query);
    setSubscriptionKeysParameter(query, keys);

    return query.getResultList();
}
 
Example 2
Project: oscm   File: APPConfigurationServiceBean.java   View Source Code Vote up 6 votes
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public HashMap<String, Setting> getControllerConfigurationSettings(
        String controllerId) throws ConfigurationException {

    LOGGER.debug("Retrieving configuration settings for controller '{}'",
            controllerId);
    HashMap<String, Setting> result = new HashMap<>();
    if (controllerId != null) {
        Query query = em
                .createNamedQuery("ConfigurationSetting.getForController");
        query.setParameter("controllerId", controllerId);
        List<?> resultList = query.getResultList();
        for (Object entry : resultList) {
            ConfigurationSetting currentCs = (ConfigurationSetting) entry;
            result.put(currentCs.getSettingKey(),
                    new Setting(currentCs.getSettingKey(),
                            currentCs.getDecryptedValue()));
        }
    }
    ControllerConfigurationKey[] keys = ControllerConfigurationKey.values();
    StringBuffer missing = new StringBuffer();
    for (int i = 0; i < keys.length; i++) {
        if (keys[i].isMandatory() && !result.containsKey(keys[i].name())) {
            if (missing.length() > 0) {
                missing.append(", ");
            }
            missing.append(keys[i].name());
        }
    }
    if (missing.length() > 0) {
        throw new ConfigurationException(
                "The controller configuration is missing the following parameter(s): "
                        + missing.toString(),
                missing.toString());
    }
    return result;
}
 
Example 3
Project: xsharing-services-router   File: StationRepositoryImpl.java   View Source Code Vote up 6 votes
/**
 * Spatial selection of CarStation entity using circle around target point
 * NOTE: the \\ notation is required for escaping the query
 *
 * @param targetX X coordinate of the target location (longitude)
 * @param targetY Y coordinate of the target location (latitude)
 * @param radius  Radius around target in meters
 * @return List of CarStation entities in range
 */
@Override
public List<CarStation> findCarStationsInRadius(Double targetX, Double targetY, Double radius) {
    String sql = "WITH index_sel AS (" +
            "SELECT s.*, st_distance(st_geomfromtext('POINT(' || ? || ' ' || ? || ')', 4326)" +
            "\\:\\:GEOGRAPHY, s.geopos\\:\\:GEOGRAPHY) AS distance " +
            "FROM carstation s " +
            "ORDER BY st_geomfromtext('POINT(' || ? || ' ' || ? || ')', 4326) <-> s.geopos) " +
            "SELECT " + getStationFieldsConcat() +
            "FROM index_sel " +
            "WHERE distance < ? ORDER BY distance;";

    Query query = entityManager.createNativeQuery(sql, CarStation.class);
    query.setParameter(1, targetX);
    query.setParameter(2, targetY);
    query.setParameter(3, targetX);
    query.setParameter(4, targetY);
    query.setParameter(5, radius);

    try {
        return query.getResultList();
    } catch (PersistenceException e) {
        // Unable to find closest Sharing Station in Database
        return Lists.newArrayList();
    }
}
 
Example 4
Project: oscm-app   File: APPConfigurationServiceBean.java   View Source Code Vote up 6 votes
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public HashMap<String, String> getControllerOrganizations() {

    LOGGER.debug("Retrieving configured controllers");
    HashMap<String, String> result = new HashMap<>();
    Query query = em
            .createNamedQuery("ConfigurationSetting.getControllersForKey");
    query.setParameter("key",
            ControllerConfigurationKey.BSS_ORGANIZATION_ID.name());
    List<?> resultList = query.getResultList();
    for (Object entry : resultList) {
        ConfigurationSetting currentCs = (ConfigurationSetting) entry;
        result.put(currentCs.getControllerId(),
                currentCs.getSettingValue());
    }
    return result;
}
 
Example 5
Project: jwala   File: WebServerCrudServiceImpl.java   View Source Code Vote up 6 votes
@Override
public void updateResourceTemplate(final String wsName, final String resourceTemplateName, final String template) {
    final Query q = entityManager.createNamedQuery(JpaWebServerConfigTemplate.UPDATE_WEBSERVER_TEMPLATE_CONTENT);
    q.setParameter("webServerName", wsName);
    q.setParameter("templateName", resourceTemplateName);
    q.setParameter("templateContent", template);

    int numEntities;
    try {
        numEntities = q.executeUpdate();
    } catch (RuntimeException re) {
        LOGGER.error("Error updating resource template {} for web server {}", resourceTemplateName, wsName, re);
        throw new ResourceTemplateUpdateException(wsName, resourceTemplateName, re);
    }

    if (numEntities == 0) {
        LOGGER.error("Error updating resource template numEntities=0 {} for web server {}", resourceTemplateName, wsName);
        throw new ResourceTemplateUpdateException(wsName, resourceTemplateName);
    }
}
 
Example 6
Project: oscm   File: LandingpageServiceBeanLocal.java   View Source Code Vote up 5 votes
private List<Product> retrieveTemplateProducts(Marketplace marketplace) {
    Query query = dm
            .createNamedQuery("Product.getActivePublishedProductTemplates");
    query.setParameter("marketplaceId", marketplace.getMarketplaceId());

    @SuppressWarnings("unchecked")
    List<Product> products = query.getResultList();
    return products;
}
 
Example 7
Project: jwala   File: ResourceDaoImpl.java   View Source Code Vote up 5 votes
@Override
public int deleteAppResource(final String templateName, final String appName, final String jvmName) {
    final Query q = em.createNamedQuery(JpaApplicationConfigTemplate.QUERY_DELETE_APP_RESOURCE_BY_TEMPLATE_APP_JVM_NAME);
    q.setParameter(JpaApplicationConfigTemplate.QUERY_PARAM_TEMPLATE_NAME, templateName);
    q.setParameter(JpaApplicationConfigTemplate.QUERY_PARAM_JVM_NAME, jvmName);
    q.setParameter(JpaApplicationConfigTemplate.QUERY_PARAM_APP_NAME, appName);
    return q.executeUpdate();
}
 
Example 8
Project: oscm   File: LdapSettingsManagementServiceBean.java   View Source Code Vote up 5 votes
public void resetOrganizationSettings(String orgId)
        throws ObjectNotFoundException {
    

    Organization organization = getOrganization(orgId);
    // first remove all existing settings
    Query query = ds
            .createNamedQuery("OrganizationSetting.removeAllForOrganization");
    query.setParameter("organization", organization);
    query.executeUpdate();

    Properties platformProps = getPlatformSettings();

    if (platformProps != null) {
        List<OrganizationSetting> settings = new ArrayList<OrganizationSetting>();
        for (Object e : platformProps.keySet()) {
            String key = (String) e;
            OrganizationSetting setting = createOrganizationSetting(
                    organization, key, "");
            settings.add(setting);
        }
        // now assign the settings to the organization
        // (may be empty if no properties provided)
        organization.setOrganizationSettings(settings);
    }

    
}
 
Example 9
Project: oscm   File: UserGroupDao.java   View Source Code Vote up 5 votes
public List<Product> getAccessibleServices(String unitId,
        Pagination pagination, String marketplaceId) {
    Query query = dm.createNamedQuery("UserGroup.findAccessibleServices");
    query.setParameter("userGroupKey", Long.valueOf(unitId));
    query.setParameter("marketplaceKey", Long.valueOf(marketplaceId));
    query.setFirstResult(pagination.getOffset());
    query.setMaxResults(pagination.getLimit());
    List<Product> accessibleProducts = ParameterizedTypes.list(
            query.getResultList(), Product.class);
    return accessibleProducts;
}
 
Example 10
Project: git-rekt   File: GuestFeedbackService.java   View Source Code Vote up 5 votes
/**
 * @return All guest feedback reports from the database that are not yet marked resolved.
 */
public List<GuestFeedback> getUnresolvedGuestFeedback() {
    String query = "FROM GuestFeedback WHERE isResolved = :param";
    Query q = entityManager.createQuery(query);
    q.setParameter("param", false);
    return q.getResultList();
}
 
Example 11
Project: esup-sgc   File: User.java   View Source Code Vote up 5 votes
public static List<Object> countNbCardsByuser(String userType) {
    EntityManager em = User.entityManager();
    String sql = "SELECT nb_cards, count(*) as count FROM user_account GROUP BY nb_cards ORDER BY count DESC";
    if (!userType.isEmpty()) {
        sql = "SELECT nb_cards, count(*) as count FROM user_account WHERE user_type = :userType GROUP BY nb_cards ORDER BY count DESC";
    }
    Query q = em.createNativeQuery(sql);
    if (!userType.isEmpty()) {
        q.setParameter("userType", userType);
    }
    return q.getResultList();
}
 
Example 12
Project: oscm   File: OnBehalfUserReferenceIT.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
private List<OnBehalfUserReference> executeQuery(Long lowerPeriodBound) {
    Query query = mgr
            .createNamedQuery("OnBehalfUserReference.findInactiveBeforePeriod");
    query.setParameter("leastPermittedTime", lowerPeriodBound);
    return query.getResultList();
}
 
Example 13
Project: oscm   File: BillingDataRetrievalServiceBean.java   View Source Code Vote up 5 votes
List<Object[]> findEventStatistics(long subscriptionKey, long startTime,
        long endTime) {
    Query queryForGatheredEvents = dm
            .createNamedQuery("GatheredEvent.getEventsForSubAndPeriod");
    queryForGatheredEvents.setParameter("startTime",
            Long.valueOf(startTime));
    queryForGatheredEvents.setParameter("endTime", Long.valueOf(endTime));
    queryForGatheredEvents.setParameter("subscriptionKey",
            Long.valueOf(subscriptionKey));
    return ParameterizedTypes.list(queryForGatheredEvents.getResultList(),
            Object[].class);
}
 
Example 14
Project: oscm   File: SharesDataRetrievalServiceBean.java   View Source Code Vote up 5 votes
@Override
@SuppressWarnings("unchecked")
public List<BillingSharesResult> loadBillingSharesResult(
        BillingSharesResultType resultType, Long startPeriod, Long endPeriod) {
    Query query = dm
            .createNamedQuery("BillingSharesResult.getSharesResult");
    query.setParameter("resultType", resultType);
    query.setParameter("fromDate", startPeriod);
    query.setParameter("toDate", endPeriod);
    return query.getResultList();
}
 
Example 15
Project: marathonv5   File: DailySalesHeatMapFacadeREST.java   View Source Code Vote up 5 votes
private HashMap<String, Long> runProductTypeQuery(Date date1, Integer productTypeId){
    long DIFF, TIME = System.currentTimeMillis(), START_TIME = System.currentTimeMillis();
    Query baseQuery = em.createQuery(BASE_TYPE_QUERY);
    Calendar cal = Calendar.getInstance();
    
    HashMap<String, Long> result = new HashMap<String, Long>();
    {
        cal.setTime(date1);
        int dayMin = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        int dayMax = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, dayMin);
        Parameter<Date> p1 = baseQuery.getParameter("oldStartDate", Date.class);
        baseQuery.setParameter(p1, cal.getTime());
        cal.set(Calendar.DAY_OF_MONTH, dayMax);
        Parameter<Date> p2 = baseQuery.getParameter("oldEndDate", Date.class);
        baseQuery.setParameter(p2, cal.getTime());
        Parameter<Integer> p3 = baseQuery.getParameter("productTypeId", Integer.class);
        baseQuery.setParameter(p3, productTypeId);

        List<Object[]> resultList = baseQuery.getResultList();

        DIFF = (System.currentTimeMillis() - TIME);
        System.out.println("    Q TIME = "+DIFF+"ms");

        for (int i=0; i < resultList.size(); i++){
            Object o[] = resultList.get(i);
            result.put((String)o[1],(Long)o[0]);
        }
    }
    
    return result;
}
 
Example 16
Project: oscm-app   File: OperationDAO.java   View Source Code Vote up 5 votes
public Operation getOperationFromQueue(String instanceId) {
    Query query = em
            .createNamedQuery("Operation.getFirstOperationFromQueue");
    query.setParameter("id", instanceId);
    query.setMaxResults(1);
    try {
        return (Operation) query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}
 
Example 17
Project: Spring-Security-Third-Edition   File: JpaAclDao.java   View Source Code Vote up 5 votes
@Override
public AclSid findAclSid(String principal) {
    Query query = entityManager.createQuery("select sid from AclSid sid where sid.sid=:sid");

    query.setParameter("sid", principal);
    List<AclSid> results = query.getResultList();
    if(results.size()>0) {
        return results.get(0);
    }
    return null;
}
 
Example 18
Project: agendamlgr   File: UsuarioFacade.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public List<Usuario> buscarUsuariosPreferencias(List<Categoria> categorias) {
    //select i from Item i join i.categoryList category where category in :categories
    if (categorias != null && !categorias.isEmpty()) {
        Query q = this.em.createQuery("select distinct u from Usuario u join u.categoriaList c where c in :categorias");
        q.setParameter("categorias", categorias);
        return (List<Usuario>) q.getResultList();
    }else{
        return (new ArrayList<>());
    }
}
 
Example 19
Project: oscm   File: BillingDataRetrievalServiceBean.java   View Source Code Vote up 5 votes
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public long loadVendorKeyForSubscription(long subscriptionKey) {
    Query query = dm.createNamedQuery("SubscriptionHistory.getVendorKey");
    query.setParameter("subscriptionKey", Long.valueOf(subscriptionKey));
    Long result = (Long) query.getSingleResult();
    return result.longValue();
}
 
Example 20
Project: oscm   File: SessionDao.java   View Source Code Vote up 4 votes
public List<Session> getActiveSessionsForUser(PlatformUser onbehalfUser) {
    Query query = dataManager
            .createNamedQuery("Session.getActiveSessionsForUser");
    query.setParameter("userKey", Long.valueOf(onbehalfUser.getKey()));
    return ParameterizedTypes.list(query.getResultList(), Session.class);
}