javax.persistence.Query

Here are the examples of the java api class javax.persistence.Query taken from open source projects.

1. StructuredContentDaoImpl#findActiveStructuredContentByNameAndType()

View license
@Override
public List<StructuredContent> findActiveStructuredContentByNameAndType(StructuredContentType type, String name, Locale fullLocale, Locale languageOnlyLocale) {
    if (languageOnlyLocale == null) {
        languageOnlyLocale = fullLocale;
    }
    final Query query = em.createNamedQuery("BC_ACTIVE_STRUCTURED_CONTENT_BY_TYPE_AND_NAME");
    query.setParameter("contentType", type);
    query.setParameter("contentName", name);
    query.setParameter("fullLocale", fullLocale);
    query.setParameter("languageOnlyLocale", languageOnlyLocale);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    return query.getResultList();
}

2. SkuDaoImpl#findSkuByURI()

Project: BroadleafCommerce
Source File: SkuDaoImpl.java
View license
@Override
public List<Sku> findSkuByURI(String uri) {
    if (extensionManager != null) {
        ExtensionResultHolder holder = new ExtensionResultHolder();
        ExtensionResultStatusType result = extensionManager.getProxy().findSkuByURI(uri, holder);
        if (ExtensionResultStatusType.HANDLED.equals(result)) {
            return (List<Sku>) holder.getResult();
        }
    }
    String skuUrlKey = uri.substring(uri.lastIndexOf('/'));
    String productUrl = uri.substring(0, uri.lastIndexOf('/'));
    Query query;
    query = em.createNamedQuery("BC_READ_SKU_BY_OUTGOING_URL");
    query.setParameter("url", uri);
    query.setParameter("productUrl", productUrl);
    query.setParameter("skuUrlKey", skuUrlKey);
    query.setParameter("currentDate", DateUtil.getCurrentDateAfterFactoringInDateResolution(cachedDate, currentDateResolution));
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    @SuppressWarnings("unchecked") List<Sku> results = query.getResultList();
    return results;
}

3. StructuredContentDaoImpl#findActiveStructuredContentByNameAndType()

View license
@Override
public List<StructuredContent> findActiveStructuredContentByNameAndType(StructuredContentType type, String name, Locale fullLocale, Locale languageOnlyLocale) {
    if (languageOnlyLocale == null) {
        languageOnlyLocale = fullLocale;
    }
    final Query query = em.createNamedQuery("BC_ACTIVE_STRUCTURED_CONTENT_BY_TYPE_AND_NAME");
    query.setParameter("contentType", type);
    query.setParameter("contentName", name);
    query.setParameter("fullLocale", fullLocale);
    query.setParameter("languageOnlyLocale", languageOnlyLocale);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    return query.getResultList();
}

4. SkuDaoImpl#findSkuByURI()

Project: broadleaf_modify
Source File: SkuDaoImpl.java
View license
@Override
public List<Sku> findSkuByURI(String uri) {
    if (extensionManager != null) {
        ExtensionResultHolder holder = new ExtensionResultHolder();
        ExtensionResultStatusType result = extensionManager.getProxy().findSkuByURI(uri, holder);
        if (ExtensionResultStatusType.HANDLED.equals(result)) {
            return (List<Sku>) holder.getResult();
        }
    }
    String skuUrlKey = uri.substring(uri.lastIndexOf('/'));
    String productUrl = uri.substring(0, uri.lastIndexOf('/'));
    Query query;
    query = em.createNamedQuery("BC_READ_SKU_BY_OUTGOING_URL");
    query.setParameter("url", uri);
    query.setParameter("productUrl", productUrl);
    query.setParameter("skuUrlKey", skuUrlKey);
    query.setParameter("currentDate", DateUtil.getCurrentDateAfterFactoringInDateResolution(cachedDate, currentDateResolution));
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    @SuppressWarnings("unchecked") List<Sku> results = query.getResultList();
    return results;
}

5. StudentCassandraTest#updateQueryTest()

Project: Kundera
Source File: StudentCassandraTest.java
View license
private void updateQueryTest() {
    Query q = em.createQuery("update StudentCassandra s set s.studentName = :newName where s.studentName = :oldName");
    q.setParameter("newName", "NewAmresh");
    q.setParameter("oldName", "Amresh");
    q.executeUpdate();
    em.clear();
    // // find by id.
    StudentEntityDef s = em.find(StudentCassandra.class, studentId1);
    Assert.assertEquals("NewAmresh", s.getStudentName());
    q = em.createQuery("update StudentCassandra s set s.studentName = :newName where s.studentName = :oldName");
    q.setParameter("newName", "Amresh");
    q.setParameter("oldName", "NewAmresh");
    q.executeUpdate();
    em.clear();
    // // find by id.
    s = em.find(StudentCassandra.class, studentId1);
    Assert.assertEquals("Amresh", s.getStudentName());
}

6. TagManagerImpl#postDelete()

Project: zstack
Source File: TagManagerImpl.java
View license
@Transactional
private void postDelete(Collection entityIds, Class entityClass) {
    List<String> rtypes = getResourceTypes(entityClass);
    String sql = "delete from SystemTagVO s where s.resourceType in (:resourceTypes) and s.resourceUuid in (:resourceUuids)";
    Query q = dbf.getEntityManager().createQuery(sql);
    q.setParameter("resourceTypes", rtypes);
    q.setParameter("resourceUuids", entityIds);
    q.executeUpdate();
    sql = "delete from UserTagVO s where s.resourceType in (:resourceTypes) and s.resourceUuid in (:resourceUuids)";
    q = dbf.getEntityManager().createQuery(sql);
    q.setParameter("resourceTypes", rtypes);
    q.setParameter("resourceUuids", entityIds);
    q.executeUpdate();
}

7. StructuredContentDaoImpl#findActiveStructuredContentByType()

View license
@Override
public List<StructuredContent> findActiveStructuredContentByType(StructuredContentType type, Locale fullLocale, Locale languageOnlyLocale) {
    String queryName = "BC_ACTIVE_STRUCTURED_CONTENT_BY_TYPE";
    if (languageOnlyLocale == null) {
        languageOnlyLocale = fullLocale;
    }
    Query query = em.createNamedQuery(queryName);
    query.setParameter("contentType", type);
    query.setParameter("fullLocale", fullLocale);
    query.setParameter("languageOnlyLocale", languageOnlyLocale);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    return query.getResultList();
}

8. StructuredContentDaoImpl#findActiveStructuredContentByName()

View license
@Override
public List<StructuredContent> findActiveStructuredContentByName(String name, Locale fullLocale, Locale languageOnlyLocale) {
    String queryName = "BC_ACTIVE_STRUCTURED_CONTENT_BY_NAME";
    if (languageOnlyLocale == null) {
        languageOnlyLocale = fullLocale;
    }
    Query query = em.createNamedQuery(queryName);
    query.setParameter("contentName", name);
    query.setParameter("fullLocale", fullLocale);
    query.setParameter("languageOnlyLocale", languageOnlyLocale);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    return query.getResultList();
}

9. ModuleConfigurationDaoImpl#readActiveByType()

View license
@SuppressWarnings("unchecked")
@Override
public List<ModuleConfiguration> readActiveByType(ModuleConfigurationType type) {
    Query query = em.createNamedQuery("BC_READ_ACTIVE_MODULE_CONFIG_BY_TYPE");
    query.setParameter("configType", type.getType());
    Date myDate = getCurrentDateAfterFactoringInDateResolution();
    query.setParameter("currentDate", myDate);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "blConfigurationModuleElements");
    return query.getResultList();
}

10. ProductDaoImpl#findProductByURI()

View license
@Override
public List<Product> findProductByURI(String uri) {
    if (extensionManager != null) {
        ExtensionResultHolder holder = new ExtensionResultHolder();
        ExtensionResultStatusType result = extensionManager.getProxy().findProductByURI(uri, holder);
        if (ExtensionResultStatusType.HANDLED.equals(result)) {
            return (List<Product>) holder.getResult();
        }
    }
    String urlKey = uri.substring(uri.lastIndexOf('/'));
    Query query;
    query = em.createNamedQuery("BC_READ_PRODUCTS_BY_OUTGOING_URL");
    query.setParameter("url", uri);
    query.setParameter("urlKey", urlKey);
    query.setParameter("currentDate", DateUtil.getCurrentDateAfterFactoringInDateResolution(cachedDate, currentDateResolution));
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    @SuppressWarnings("unchecked") List<Product> results = query.getResultList();
    return results;
}

11. StructuredContentDaoImpl#findActiveStructuredContentByType()

View license
@Override
public List<StructuredContent> findActiveStructuredContentByType(StructuredContentType type, Locale fullLocale, Locale languageOnlyLocale) {
    String queryName = "BC_ACTIVE_STRUCTURED_CONTENT_BY_TYPE";
    if (languageOnlyLocale == null) {
        languageOnlyLocale = fullLocale;
    }
    Query query = em.createNamedQuery(queryName);
    query.setParameter("contentType", type);
    query.setParameter("fullLocale", fullLocale);
    query.setParameter("languageOnlyLocale", languageOnlyLocale);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    return query.getResultList();
}

12. StructuredContentDaoImpl#findActiveStructuredContentByName()

View license
@Override
public List<StructuredContent> findActiveStructuredContentByName(String name, Locale fullLocale, Locale languageOnlyLocale) {
    String queryName = "BC_ACTIVE_STRUCTURED_CONTENT_BY_NAME";
    if (languageOnlyLocale == null) {
        languageOnlyLocale = fullLocale;
    }
    Query query = em.createNamedQuery(queryName);
    query.setParameter("contentName", name);
    query.setParameter("fullLocale", fullLocale);
    query.setParameter("languageOnlyLocale", languageOnlyLocale);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    return query.getResultList();
}

13. ModuleConfigurationDaoImpl#readActiveByType()

View license
@SuppressWarnings("unchecked")
@Override
public List<ModuleConfiguration> readActiveByType(ModuleConfigurationType type) {
    Query query = em.createNamedQuery("BC_READ_ACTIVE_MODULE_CONFIG_BY_TYPE");
    query.setParameter("configType", type.getType());
    Date myDate = getCurrentDateAfterFactoringInDateResolution();
    query.setParameter("currentDate", myDate);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "blConfigurationModuleElements");
    return query.getResultList();
}

14. ProductDaoImpl#findProductByURI()

View license
@Override
public List<Product> findProductByURI(String uri) {
    if (extensionManager != null) {
        ExtensionResultHolder holder = new ExtensionResultHolder();
        ExtensionResultStatusType result = extensionManager.getProxy().findProductByURI(uri, holder);
        if (ExtensionResultStatusType.HANDLED.equals(result)) {
            return (List<Product>) holder.getResult();
        }
    }
    String urlKey = uri.substring(uri.lastIndexOf('/'));
    Query query;
    query = em.createNamedQuery("BC_READ_PRODUCTS_BY_OUTGOING_URL");
    query.setParameter("url", uri);
    query.setParameter("urlKey", urlKey);
    query.setParameter("currentDate", DateUtil.getCurrentDateAfterFactoringInDateResolution(cachedDate, currentDateResolution));
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    @SuppressWarnings("unchecked") List<Product> results = query.getResultList();
    return results;
}

15. JDBCStateStore#getExecutionInstances()

Project: falcon
Source File: JDBCStateStore.java
View license
@Override
public Collection<InstanceState> getExecutionInstances(Entity entity, String cluster, Collection<InstanceState.STATE> states, DateTime start, DateTime end) throws StateStoreException {
    String entityKey = new EntityClusterID(entity, cluster).getEntityID().getKey();
    EntityManager entityManager = getEntityManager();
    Query q = entityManager.createNamedQuery(PersistenceConstants.GET_INSTANCES_FOR_ENTITY_CLUSTER_FOR_STATES_WITH_RANGE);
    q.setParameter("entityId", entityKey);
    List<String> instanceStates = new ArrayList<>();
    for (InstanceState.STATE state : states) {
        instanceStates.add(state.toString());
    }
    q.setParameter("currentState", instanceStates);
    q.setParameter("startTime", new Timestamp(start.getMillis()));
    q.setParameter("endTime", new Timestamp(end.getMillis()));
    q.setParameter("cluster", cluster);
    List result = q.getResultList();
    entityManager.close();
    try {
        return BeanMapperUtil.convertToInstanceState(result);
    } catch (IOException e) {
        throw new StateStoreException(e);
    }
}

16. JpaStorage#getAllPolicies()

Project: apiman
Source File: JpaStorage.java
View license
/**
     * @see io.apiman.manager.api.core.IStorage#getAllPolicies(java.lang.String, java.lang.String, java.lang.String, io.apiman.manager.api.beans.policies.PolicyType)
     */
@Override
public Iterator<PolicyBean> getAllPolicies(String organizationId, String entityId, String version, PolicyType type) throws StorageException {
    EntityManager entityManager = getActiveEntityManager();
    String jpql = "SELECT p from PolicyBean p " + " WHERE p.organizationId = :orgId " + "   AND p.entityId = :entityId " + "   AND p.entityVersion = :entityVersion " + "   AND p.type = :type" + " ORDER BY p.orderIndex ASC";
    Query query = entityManager.createQuery(jpql);
    query.setParameter("orgId", organizationId);
    query.setParameter("entityId", entityId);
    query.setParameter("entityVersion", version);
    query.setParameter("type", type);
    return getAll(PolicyBean.class, query);
}

17. PageDaoImpl#findPageByURI()

Project: BroadleafCommerce
Source File: PageDaoImpl.java
View license
@Override
public List<Page> findPageByURI(Locale fullLocale, Locale languageOnlyLocale, String uri) {
    Query query;
    if (languageOnlyLocale == null) {
        languageOnlyLocale = fullLocale;
    }
    query = em.createNamedQuery("BC_READ_PAGE_BY_URI");
    query.setParameter("fullLocale", fullLocale);
    query.setParameter("languageOnlyLocale", languageOnlyLocale);
    query.setParameter("uri", uri);
    return query.getResultList();
}

18. CategoryDaoImpl#findCategoryByURI()

View license
@Override
public Category findCategoryByURI(String uri) {
    if (extensionManager != null) {
        ExtensionResultHolder holder = new ExtensionResultHolder();
        ExtensionResultStatusType result = extensionManager.getProxy().findCategoryByURI(uri, holder);
        if (ExtensionResultStatusType.HANDLED.equals(result)) {
            return (Category) holder.getResult();
        }
    }
    Query query;
    query = em.createNamedQuery("BC_READ_CATEGORY_OUTGOING_URL");
    query.setParameter("currentDate", getCurrentDateAfterFactoringInDateResolution());
    query.setParameter("url", uri);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    @SuppressWarnings("unchecked") List<Category> results = query.getResultList();
    if (results != null && !results.isEmpty()) {
        return results.get(0);
    } else {
        return null;
    }
}

19. FulfillmentGroupDaoImpl#readFulfillmentGroupsByStatus()

View license
@SuppressWarnings("unchecked")
@Override
public List<FulfillmentGroup> readFulfillmentGroupsByStatus(FulfillmentGroupStatusType status, int start, int maxResults, boolean ascending) {
    Query query = null;
    if (ascending) {
        query = em.createNamedQuery("BC_READ_FULFILLMENT_GROUP_BY_STATUS_ASC");
    } else {
        query = em.createNamedQuery("BC_READ_FULFILLMENT_GROUP_BY_STATUS_DESC");
    }
    query.setParameter("status", status.getType());
    query.setFirstResult(start);
    query.setMaxResults(maxResults);
    return query.getResultList();
}

20. OrderDaoImpl#readCartForCustomer()

Project: BroadleafCommerce
Source File: OrderDaoImpl.java
View license
@Override
public Order readCartForCustomer(final Customer customer) {
    Order order = null;
    final Query query = em.createNamedQuery("BC_READ_ORDERS_BY_CUSTOMER_ID_AND_NAME_NULL");
    query.setParameter("customerId", customer.getId());
    query.setParameter("orderStatus", OrderStatus.IN_PROCESS.getType());
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Order");
    @SuppressWarnings("rawtypes") final List temp = query.getResultList();
    if (temp != null && !temp.isEmpty()) {
        order = (Order) temp.get(0);
    }
    return order;
}

21. RatingSummaryDaoImpl#readRatingSummary()

View license
@Override
public RatingSummary readRatingSummary(final String itemId, final RatingType type) {
    final Query query = em.createNamedQuery("BC_READ_RATING_SUMMARY_BY_ITEM_ID_AND_TYPE");
    query.setParameter("itemId", itemId);
    query.setParameter("ratingType", type.getType());
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    RatingSummary ratingSummary = null;
    try {
        ratingSummary = (RatingSummary) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return ratingSummary;
}

22. RatingSummaryDaoImpl#readRating()

View license
@Override
public RatingDetail readRating(final Long customerId, final Long ratingSummaryId) {
    final Query query = em.createNamedQuery("BC_READ_RATING_DETAIL_BY_CUSTOMER_ID_AND_RATING_SUMMARY_ID");
    query.setParameter("customerId", customerId);
    query.setParameter("ratingSummaryId", ratingSummaryId);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    RatingDetail ratingDetail = null;
    try {
        ratingDetail = (RatingDetail) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return ratingDetail;
}

23. RatingSummaryDaoImpl#readReview()

View license
@Override
public ReviewDetail readReview(final Long customerId, final Long ratingSummaryId) {
    final Query query = em.createNamedQuery("BC_READ_REVIEW_DETAIL_BY_CUSTOMER_ID_AND_RATING_SUMMARY_ID");
    query.setParameter("customerId", customerId);
    query.setParameter("ratingSummaryId", ratingSummaryId);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    ReviewDetail reviewDetail = null;
    try {
        reviewDetail = (ReviewDetail) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return reviewDetail;
}

24. SearchRedirectDaoImpl#findSearchRedirectBySearchTerm()

View license
@Override
public SearchRedirect findSearchRedirectBySearchTerm(String searchTerm) {
    Query query;
    query = em.createNamedQuery("BC_READ_SEARCH_URL");
    query.setParameter("searchTerm", searchTerm);
    query.setParameter("now", getCurrentDateAfterFactoringInDateResolution());
    query.setMaxResults(1);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    List<SearchRedirect> results = query.getResultList();
    if (results != null && !results.isEmpty()) {
        return results.get(0);
    } else {
        return null;
    }
}

25. PageDaoImpl#findPageByURI()

Project: broadleaf_modify
Source File: PageDaoImpl.java
View license
@Override
public List<Page> findPageByURI(Locale fullLocale, Locale languageOnlyLocale, String uri) {
    Query query;
    if (languageOnlyLocale == null) {
        languageOnlyLocale = fullLocale;
    }
    query = em.createNamedQuery("BC_READ_PAGE_BY_URI");
    query.setParameter("fullLocale", fullLocale);
    query.setParameter("languageOnlyLocale", languageOnlyLocale);
    query.setParameter("uri", uri);
    return query.getResultList();
}

26. CategoryDaoImpl#findCategoryByURI()

View license
@Override
public Category findCategoryByURI(String uri) {
    if (extensionManager != null) {
        ExtensionResultHolder holder = new ExtensionResultHolder();
        ExtensionResultStatusType result = extensionManager.getProxy().findCategoryByURI(uri, holder);
        if (ExtensionResultStatusType.HANDLED.equals(result)) {
            return (Category) holder.getResult();
        }
    }
    Query query;
    query = em.createNamedQuery("BC_READ_CATEGORY_OUTGOING_URL");
    query.setParameter("currentDate", getCurrentDateAfterFactoringInDateResolution());
    query.setParameter("url", uri);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    @SuppressWarnings("unchecked") List<Category> results = query.getResultList();
    if (results != null && !results.isEmpty()) {
        return results.get(0);
    } else {
        return null;
    }
}

27. FulfillmentGroupDaoImpl#readFulfillmentGroupsByStatus()

View license
@SuppressWarnings("unchecked")
@Override
public List<FulfillmentGroup> readFulfillmentGroupsByStatus(FulfillmentGroupStatusType status, int start, int maxResults, boolean ascending) {
    Query query = null;
    if (ascending) {
        query = em.createNamedQuery("BC_READ_FULFILLMENT_GROUP_BY_STATUS_ASC");
    } else {
        query = em.createNamedQuery("BC_READ_FULFILLMENT_GROUP_BY_STATUS_DESC");
    }
    query.setParameter("status", status.getType());
    query.setFirstResult(start);
    query.setMaxResults(maxResults);
    return query.getResultList();
}

28. OrderDaoImpl#readCartForCustomer()

Project: broadleaf_modify
Source File: OrderDaoImpl.java
View license
@Override
public Order readCartForCustomer(final Customer customer) {
    Order order = null;
    final Query query = em.createNamedQuery("BC_READ_ORDERS_BY_CUSTOMER_ID_AND_NAME_NULL");
    query.setParameter("customerId", customer.getId());
    query.setParameter("orderStatus", OrderStatus.IN_PROCESS.getType());
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Order");
    @SuppressWarnings("rawtypes") final List temp = query.getResultList();
    if (temp != null && !temp.isEmpty()) {
        order = (Order) temp.get(0);
    }
    return order;
}

29. RatingSummaryDaoImpl#readRatingSummary()

View license
@Override
public RatingSummary readRatingSummary(final String itemId, final RatingType type) {
    final Query query = em.createNamedQuery("BC_READ_RATING_SUMMARY_BY_ITEM_ID_AND_TYPE");
    query.setParameter("itemId", itemId);
    query.setParameter("ratingType", type.getType());
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    RatingSummary ratingSummary = null;
    try {
        ratingSummary = (RatingSummary) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return ratingSummary;
}

30. RatingSummaryDaoImpl#readRating()

View license
@Override
public RatingDetail readRating(final Long customerId, final Long ratingSummaryId) {
    final Query query = em.createNamedQuery("BC_READ_RATING_DETAIL_BY_CUSTOMER_ID_AND_RATING_SUMMARY_ID");
    query.setParameter("customerId", customerId);
    query.setParameter("ratingSummaryId", ratingSummaryId);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    RatingDetail ratingDetail = null;
    try {
        ratingDetail = (RatingDetail) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return ratingDetail;
}

31. RatingSummaryDaoImpl#readReview()

View license
@Override
public ReviewDetail readReview(final Long customerId, final Long ratingSummaryId) {
    final Query query = em.createNamedQuery("BC_READ_REVIEW_DETAIL_BY_CUSTOMER_ID_AND_RATING_SUMMARY_ID");
    query.setParameter("customerId", customerId);
    query.setParameter("ratingSummaryId", ratingSummaryId);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
    ReviewDetail reviewDetail = null;
    try {
        reviewDetail = (ReviewDetail) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return reviewDetail;
}

32. SearchRedirectDaoImpl#findSearchRedirectBySearchTerm()

View license
@Override
public SearchRedirect findSearchRedirectBySearchTerm(String searchTerm) {
    Query query;
    query = em.createNamedQuery("BC_READ_SEARCH_URL");
    query.setParameter("searchTerm", searchTerm);
    query.setParameter("now", getCurrentDateAfterFactoringInDateResolution());
    query.setMaxResults(1);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    List<SearchRedirect> results = query.getResultList();
    if (results != null && !results.isEmpty()) {
        return results.get(0);
    } else {
        return null;
    }
}

33. JDBCStateStore#updateEntity()

Project: falcon
Source File: JDBCStateStore.java
View license
@Override
public void updateEntity(EntityState entityState) throws StateStoreException {
    EntityID entityID = new EntityID(entityState.getEntity());
    if (!entityExists(entityID)) {
        throw new StateStoreException("Entity with key, " + entityID + " doesn't exists.");
    }
    EntityManager entityManager = getEntityManager();
    beginTransaction(entityManager);
    Query q = entityManager.createNamedQuery(PersistenceConstants.UPDATE_ENTITY);
    q.setParameter("id", entityID.getKey());
    if (entityState.getCurrentState() != null) {
        q.setParameter("state", entityState.getCurrentState().toString());
    }
    q.setParameter("type", entityState.getEntity().getEntityType().toString());
    q.setParameter("name", entityState.getEntity().getName());
    q.executeUpdate();
    commitAndCloseTransaction(entityManager);
}

34. JDBCStateStore#getExecutionInstanceSummary()

Project: falcon
Source File: JDBCStateStore.java
View license
@Override
public Map<InstanceState.STATE, Long> getExecutionInstanceSummary(Entity entity, String cluster, DateTime start, DateTime end) throws StateStoreException {
    String entityKey = new EntityClusterID(entity, cluster).getEntityID().getKey();
    EntityManager entityManager = getEntityManager();
    Query q = entityManager.createNamedQuery(PersistenceConstants.GET_INSTANCE_SUMMARY_BY_STATE_WITH_RANGE);
    q.setParameter("entityId", entityKey);
    q.setParameter("cluster", cluster);
    q.setParameter("startTime", new Timestamp(start.getMillis()));
    q.setParameter("endTime", new Timestamp(end.getMillis()));
    List result = q.getResultList();
    entityManager.close();
    return BeanMapperUtil.getInstanceStateSummary(result);
}

35. IMDBJPAQueriesTest#findActorByIDAndName()

Project: Kundera
Source File: IMDBJPAQueriesTest.java
View license
private void findActorByIDAndName() {
    // Positive scenario
    Query query = em.createQuery("select a from Actor a where a.id=:id AND a.name=:name");
    query.setParameter("id", 1);
    query.setParameter("name", "Tom Cruise");
    List<Actor> actors = query.getResultList();
    Assert.assertNotNull(actors);
    Assert.assertFalse(actors.isEmpty());
    Assert.assertEquals(1, actors.size());
    assertActor1(actors.get(0));
    // Negative scenario
    query = em.createQuery("select a from Actor a where a.id=:id AND a.name=:name");
    query.setParameter("id", 2);
    query.setParameter("name", "Tom Cruise");
    actors = query.getResultList();
    Assert.assertTrue(actors == null || actors.isEmpty());
}

36. PersonRdbmsTest#testPagination()

Project: Kundera
Source File: PersonRdbmsTest.java
View license
private void testPagination() {
    Query findQuery = em.createQuery("Select p from PersonRDBMS p");
    findQuery.setFirstResult(1);
    findQuery.setMaxResults(2);
    List<PersonRDBMS> allPersons = findQuery.getResultList();
    Assert.assertEquals(2, allPersons.size());
    Assert.assertEquals("2", allPersons.get(0).getPersonId());
    Assert.assertEquals("3", allPersons.get(1).getPersonId());
    //extremes
    findQuery.setFirstResult(5);
    findQuery.setMaxResults(10);
    allPersons = findQuery.getResultList();
    Assert.assertNotNull(allPersons);
    Assert.assertTrue(allPersons.isEmpty());
}

37. LOSLotServiceBean#getListByName()

Project: myWMS
Source File: LOSLotServiceBean.java
View license
@SuppressWarnings("unchecked")
public List<Lot> getListByName(Client client, String lotName, String itemDataNumber) {
    Query query = manager.createQuery("SELECT lot FROM " + Lot.class.getSimpleName() + " lot " + "WHERE lot.name=:name " + " AND lot.client=:cl " + " AND lot.itemData.number=:idat " + " AND lot.itemData.client=:cl ");
    query.setParameter("name", lotName);
    query.setParameter("idat", itemDataNumber);
    query.setParameter("cl", client);
    return query.getResultList();
}

38. LOSRackServiceBean#getByPosition()

Project: myWMS
Source File: LOSRackServiceBean.java
View license
//------------------------------------------------------------------------
public LOSStorageLocation getByPosition(LOSRack r, int x, int y, int z) {
    StringBuffer sb = new StringBuffer("SELECT rl FROM ");
    sb.append(LOSStorageLocation.class.getSimpleName() + " rl ");
    sb.append("WHERE rl.rack=:rack ");
    sb.append("AND rl.XPos=:x ");
    sb.append("AND rl.YPos=:y ");
    sb.append("AND rl.ZPos=:z");
    Query query = manager.createQuery(sb.toString());
    query.setParameter("rack", r);
    query.setParameter("x", x);
    query.setParameter("y", y);
    query.setParameter("z", z);
    try {
        LOSStorageLocation rl = (LOSStorageLocation) query.getSingleResult();
        return rl;
    } catch (NoResultException nre) {
        return null;
    }
}

39. AuthenticationTokenDao#deleteOldSessionToken()

Project: reader
Source File: AuthenticationTokenDao.java
View license
/**
     * Deletes old short lived tokens.
     *
     * @param userId User ID
     */
public void deleteOldSessionToken(String userId) {
    StringBuilder sb = new StringBuilder("delete from T_AUTHENTICATION_TOKEN AS ato ");
    sb.append(" where ato.AUT_IDUSER_C = :userId and ato.AUT_LONGLASTED_B = :longLasted");
    sb.append(" and ato.AUT_LASTCONNECTIONDATE_D < :minDate ");
    EntityManager em = ThreadLocalContext.get().getEntityManager();
    Query q = em.createNativeQuery(sb.toString());
    q.setParameter("userId", userId);
    q.setParameter("longLasted", false);
    q.setParameter("minDate", DateTime.now().minusDays(1).toDate());
    q.executeUpdate();
}

40. KeyValueFacadeImpl#delete()

Project: zstack
Source File: KeyValueFacadeImpl.java
View license
@Override
@Transactional
public void delete(String uuid) {
    String sql = "delete from KeyValueVO vo where vo.uuid = :uuid";
    Query q = dbf.getEntityManager().createQuery(sql);
    q.setParameter("uuid", uuid);
    q.executeUpdate();
    sql = "delete from KeyValueBinaryVO vo where vo.uuid = :uuid";
    q = dbf.getEntityManager().createQuery(sql);
    q.setParameter("uuid", uuid);
    q.executeUpdate();
}

41. JpaStorage#getAllContracts()

Project: apiman
Source File: JpaStorage.java
View license
/**
     * @see io.apiman.manager.api.core.IStorage#getAllContracts(java.lang.String, java.lang.String, java.lang.String)
     */
@Override
public Iterator<ContractBean> getAllContracts(String organizationId, String clientId, String version) throws StorageException {
    EntityManager entityManager = getActiveEntityManager();
    String jpql = "SELECT c from ContractBean c " + "  JOIN c.client clientv " + "  JOIN clientv.client client " + "  JOIN client.organization aorg" + " WHERE client.id = :clientId " + "   AND aorg.id = :orgId " + "   AND clientv.version = :version " + " ORDER BY c.id ASC";
    Query query = entityManager.createQuery(jpql);
    query.setParameter("orgId", organizationId);
    query.setParameter("clientId", clientId);
    query.setParameter("version", version);
    return getAll(ContractBean.class, query);
}

42. DatabaseNetwork#findAllLike()

Project: BotLibre
Source File: DatabaseNetwork.java
View license
/**
	 * Return all vertices matching the filter.
	 */
@SuppressWarnings("unchecked")
public synchronized List<Vertex> findAllLike(String filter, int pageSize, int page) {
    Query query = null;
    if (filter.indexOf('*') == -1) {
        query = this.entityManager.createQuery("Select v from Vertex v where v.dataValue = :filter");
        query.setParameter("filter", filter);
    } else {
        query = this.entityManager.createQuery("Select v from Vertex v where v.dataValue like :filter");
        query.setParameter("filter", filter.replace('*', '%'));
    }
    setHints(query);
    query.setFirstResult(page * pageSize);
    query.setMaxResults(pageSize);
    return query.getResultList();
}

43. DatabaseReadOnlyNetwork#findByData()

View license
/**
	 * Return the vertex with the given data.
	 */
public synchronized Vertex findByData(Object data) {
    if (data == null) {
        return null;
    }
    Vertex vertex = this.verticiesByData.get(data);
    if (vertex != null) {
        return vertex;
    }
    Query query = getEntityManager().createNamedQuery("findVertexByData");
    query.setHint(QueryHints.READ_ONLY, true);
    query.setParameter("data", BasicVertex.convertDataValue(data));
    query.setParameter("type", BasicVertex.convertDataType(data));
    try {
        vertex = (Vertex) query.getSingleResult();
        if (this.verticiesByData.size() < MAX_SIZE) {
            this.verticiesByData.put(vertex.getData(), vertex);
        }
        return vertex;
    } catch (NoResultException notFound) {
        return null;
    }
}

44. ShippingRateDaoImpl#readShippingRateByFeeTypesUnityQty()

View license
@Override
@SuppressWarnings("unchecked")
public ShippingRate readShippingRateByFeeTypesUnityQty(String feeType, String feeSubType, BigDecimal unitQuantity) {
    Query query = em.createNamedQuery("BC_READ_FIRST_SHIPPING_RATE_BY_FEE_TYPES");
    query.setParameter("feeType", feeType);
    query.setParameter("feeSubType", feeSubType);
    query.setParameter("bandUnitQuantity", unitQuantity);
    List<ShippingRate> returnedRates = query.getResultList();
    if (returnedRates.size() > 0) {
        return returnedRates.get(0);
    } else {
        return null;
    }
}

45. ShippingRateDaoImpl#readShippingRateByFeeTypesUnityQty()

View license
@Override
@SuppressWarnings("unchecked")
public ShippingRate readShippingRateByFeeTypesUnityQty(String feeType, String feeSubType, BigDecimal unitQuantity) {
    Query query = em.createNamedQuery("BC_READ_FIRST_SHIPPING_RATE_BY_FEE_TYPES");
    query.setParameter("feeType", feeType);
    query.setParameter("feeSubType", feeSubType);
    query.setParameter("bandUnitQuantity", unitQuantity);
    List<ShippingRate> returnedRates = query.getResultList();
    if (returnedRates.size() > 0) {
        return returnedRates.get(0);
    } else {
        return null;
    }
}

46. MonitoringJdbcStateStore#deletePendingInstance()

View license
public void deletePendingInstance(String feedName, String clusterName, Date nominalTime) {
    EntityManager entityManager = getEntityManager();
    beginTransaction(entityManager);
    Query q = entityManager.createNamedQuery(PersistenceConstants.DELETE_PENDING_NOMINAL_INSTANCES);
    q.setParameter("feedName", feedName);
    q.setParameter("clusterName", clusterName);
    q.setParameter("nominalTime", nominalTime);
    try {
        q.executeUpdate();
    } finally {
        commitAndCloseTransaction(entityManager);
    }
}

47. MonitoringJdbcStateStore#updateSLAAlertInstance()

View license
public void updateSLAAlertInstance(String feedName, String clusterName, Date nominalTime) {
    EntityManager entityManager = getEntityManager();
    beginTransaction(entityManager);
    Query q = entityManager.createNamedQuery(PersistenceConstants.UPDATE_SLA_HIGH);
    q.setParameter("feedName", feedName);
    q.setParameter("clusterName", clusterName);
    q.setParameter("nominalTime", nominalTime);
    try {
        q.executeUpdate();
    } finally {
        commitAndCloseTransaction(entityManager);
    }
}

48. MonitoringJdbcStateStore#deleteFeedAlertInstance()

View license
public void deleteFeedAlertInstance(String feedName, String clusterName, Date nominalTime) {
    EntityManager entityManager = getEntityManager();
    beginTransaction(entityManager);
    Query q = entityManager.createNamedQuery(PersistenceConstants.DELETE_FEED_ALERT_INSTANCE);
    q.setParameter("feedName", feedName);
    q.setParameter("clusterName", clusterName);
    q.setParameter("nominalTime", nominalTime);
    try {
        q.executeUpdate();
    } finally {
        commitAndCloseTransaction(entityManager);
    }
}

49. JDBCStateStore#getExecutionInstances()

Project: falcon
Source File: JDBCStateStore.java
View license
@Override
public Collection<InstanceState> getExecutionInstances(Entity entity, String cluster, Collection<InstanceState.STATE> states) throws StateStoreException {
    EntityClusterID entityClusterID = new EntityClusterID(entity, cluster);
    String entityKey = entityClusterID.getEntityID().getKey();
    EntityManager entityManager = getEntityManager();
    Query q = entityManager.createNamedQuery(PersistenceConstants.GET_INSTANCES_FOR_ENTITY_CLUSTER_FOR_STATES);
    q.setParameter("entityId", entityKey);
    q.setParameter("cluster", cluster);
    List<String> instanceStates = new ArrayList<>();
    for (InstanceState.STATE state : states) {
        instanceStates.add(state.toString());
    }
    q.setParameter("currentState", instanceStates);
    List result = q.getResultList();
    entityManager.close();
    try {
        return BeanMapperUtil.convertToInstanceState(result);
    } catch (IOException e) {
        throw new StateStoreException(e);
    }
}

50. JDBCStateStore#getLastExecutionInstance()

Project: falcon
Source File: JDBCStateStore.java
View license
@Override
public InstanceState getLastExecutionInstance(Entity entity, String cluster) throws StateStoreException {
    String key = new EntityClusterID(entity, cluster).getEntityID().getKey();
    EntityManager entityManager = getEntityManager();
    Query q = entityManager.createNamedQuery(PersistenceConstants.GET_LAST_INSTANCE_FOR_ENTITY_CLUSTER);
    q.setParameter("entityId", key);
    q.setParameter("cluster", cluster);
    q.setMaxResults(1);
    List result = q.getResultList();
    entityManager.close();
    if (!result.isEmpty()) {
        try {
            return BeanMapperUtil.convertToInstanceState((InstanceBean) result.get(0));
        } catch (IOException e) {
            throw new StateStoreException(e);
        }
    }
    return null;
}

51. JPAPolicyStore#findByScopeIds()

Project: keycloak
Source File: JPAPolicyStore.java
View license
@Override
public List<Policy> findByScopeIds(List<String> scopeIds, String resourceServerId) {
    if (scopeIds == null || scopeIds.isEmpty()) {
        return Collections.emptyList();
    }
    // Use separate subquery to handle DB2 and MSSSQL
    Query query = getEntityManager().createQuery("select pe from PolicyEntity pe where pe.id IN (select p.id from PolicyEntity p inner join p.scopes s where p.resourceServer.id = :serverId and s.id in (:scopeIds) and p.resources is empty group by p.id) order by pe.name");
    query.setParameter("serverId", resourceServerId);
    query.setParameter("scopeIds", scopeIds);
    return query.getResultList();
}

52. CassandraNativeFunctionsTest#testSelectAndInsertJSON()

View license
/**
     * Test select and insert json.
     */
@Test
public void testSelectAndInsertJSON() {
    String useNativeSql = "USE " + "\"KunderaExamples\"";
    Query q = entityManager.createNativeQuery(useNativeSql);
    q.executeUpdate();
    // create user defined function
    String insertJSON = "Insert into \"PERSONCASSANDRA\" JSON '{\"\\\"PERSON_NAME\\\"\": \"kundera\", \"\\\"AGE\\\"\": 123, \"\\\"personId\\\"\":\"abc\" }'";
    q = entityManager.createNativeQuery(insertJSON);
    q.executeUpdate();
    // Assert values
    String qry = "Select JSON * from \"PERSONCASSANDRA\"";
    q = entityManager.createNativeQuery(qry);
    List persons = q.getResultList();
    Assert.assertNotNull(persons);
    Assert.assertFalse(persons.isEmpty());
    Assert.assertEquals(6, persons.size());
    q = entityManager.createNativeQuery("Delete from \"PERSONCASSANDRA\" where \"personId\" = 'abc'");
    q.executeUpdate();
}

53. EmbeddedEntityTest#testSelectTwoSpecificColumnOfEmbeddable()

Project: Kundera
Source File: EmbeddedEntityTest.java
View license
@Test
public void testSelectTwoSpecificColumnOfEmbeddable() {
    persist();
    String query2 = "select x.id.captureTime," + "x.id.server," + "x.rowKey," + "x.established, " + "x.closeWait," + "x.finWait," + "x.finWait2," + "x.idle," + "x.listen," + "x.synRecv," + "x.timeWait," + "x.total " + "from NetstatData x " + "where x.id.portMapTypeCd= :port" + " and x.id.captureTime between :captureTime1 and :captureTime2";
    Query query = em.createQuery(query2);
    query.setParameter("port", "portMapTypeCd");
    query.setParameter("captureTime1", CAPTURE_TIME1);
    query.setParameter("captureTime2", CAPTURE_TIME3);
    List<NetstatData> result = query.getResultList();
    Assert.assertNotNull(result);
    Assert.assertEquals(2, result.size());
    Assert.assertNotNull(result.get(0));
    Assert.assertNotNull(result.get(0).getId());
    Assert.assertNull(result.get(0).getId().getPortMapId());
}

54. EmbeddedEntityTest#testSelectTwoColumnsOfEmbeddable()

Project: Kundera
Source File: EmbeddedEntityTest.java
View license
@Test
public void testSelectTwoColumnsOfEmbeddable() {
    persist();
    String query2 = "select x.id.captureTime," + "x.id.server," + "x.rowKey," + "x.established, " + "x.closeWait," + "x.finWait," + "x.finWait2," + "x.idle," + "x.listen," + "x.synRecv," + "x.timeWait," + "x.total " + "from NetstatData x " + "where x.id.server= :serverId" + " and x.id.captureTime between :captureTime1 and :captureTime2";
    Query query = em.createQuery(query2);
    query.setParameter("serverId", "apdwa571");
    query.setParameter("captureTime1", CAPTURE_TIME1);
    query.setParameter("captureTime2", CAPTURE_TIME3);
    List<NetstatData> result = query.getResultList();
    Assert.assertNotNull(result);
    Assert.assertEquals(1, result.size());
    Assert.assertNotNull(result.get(0));
    Assert.assertNotNull(result.get(0).getId());
    Assert.assertEquals(CAPTURE_TIME3, result.get(0).getId().getCaptureTime());
    Assert.assertEquals("apdwa571", result.get(0).getId().getServer());
    Assert.assertNull(result.get(0).getId().getPortMapId());
}

55. IMDBJPAQueriesTest#findMoviesUsingIdOrTitleOrYear()

Project: Kundera
Source File: IMDBJPAQueriesTest.java
View license
private void findMoviesUsingIdOrTitleOrYear() {
    Query query = em.createQuery("select m from Movie m where m.id = :movieId OR m.title like :title OR m.year = :year");
    query.setParameter("movieId", "m1");
    query.setParameter("title", "Miss");
    query.setParameter("year", 2009);
    List<Movie> movies = query.getResultList();
    Assert.assertNotNull(movies);
    Assert.assertFalse(movies.isEmpty());
    Assert.assertEquals(3, movies.size());
    for (Movie movie : movies) {
        Assert.assertNotNull(movie);
        Assert.assertTrue(movie.getId().equals("m1") || movie.getId().equals("m2") || movie.getId().equals("m3"));
    }
}

56. RedisGeneratedIdTest#purge()

Project: Kundera
Source File: RedisGeneratedIdTest.java
View license
/**
     * 
     */
private void purge() {
    // Delete by query.
    String deleteQuery = "Delete from RedisGeneratedIdStrategySequence r";
    Query query = em.createQuery(deleteQuery);
    query.executeUpdate();
    deleteQuery = "Delete from RedisGeneratedIdWithOutSequenceGenerator r";
    query = em.createQuery(deleteQuery);
    query.executeUpdate();
    deleteQuery = "Delete from RedisGeneratedIdWithSequenceGenerator r";
    query = em.createQuery(deleteQuery);
    query.executeUpdate();
}

57. RedisESIndexerTest#testMultipleORClause()

Project: Kundera
Source File: RedisESIndexerTest.java
View license
/**
     * Test multiple or clause.
     */
private void testMultipleORClause() {
    Query query;
    List<PersonRedis> results;
    String findByIdMoreOrAge = "Select p from PersonRedis p where p.personId=:personId OR p.age=:age OR p.personName=:personName";
    query = em.createQuery(findByIdMoreOrAge);
    query.setParameter("personId", ROW_KEY);
    query.setParameter("age", 29);
    query.setParameter("personName", "amit");
    results = query.getResultList();
    Assert.assertEquals(3, results.size());
}

58. SparkCassClientTest#testSaveIntermediateResult()

Project: Kundera
Source File: SparkCassClientTest.java
View license
/**
     * Save intermediate result.
     */
private void testSaveIntermediateResult() {
    CassandraCli.executeCqlQuery("CREATE TABLE IF NOT EXISTS spark_book_copy (id text PRIMARY KEY, title text, author text, category text, \"numPages\" int)", "sparktest");
    String sqlString = "INSERT INTO cassandra.sparktest.spark_book_copy FROM (select * from spark_book)";
    Query q = em.createNativeQuery(sqlString, Book.class);
    q.executeUpdate();
    sqlString = "INSERT INTO fs.[src/test/resources/testspark_csv] AS CSV FROM (select * from spark_book)";
    q = em.createNativeQuery(sqlString, Book.class);
    q.executeUpdate();
    sqlString = "INSERT INTO fs.[src/test/resources/testspark_json] AS JSON FROM (select * from spark_book)";
    q = em.createNativeQuery(sqlString, Book.class);
    q.executeUpdate();
}

59. SparkHiveClientTest#testSaveIntermediateResult()

Project: Kundera
Source File: SparkHiveClientTest.java
View license
/**
     * Test save intermediate result.
     */
private void testSaveIntermediateResult() {
    String sqlString = "INSERT INTO hive.sparktest.IntermediatePerson FROM (select * from person)";
    Query q = em.createNativeQuery(sqlString, PersonHive.class);
    q.executeUpdate();
    List<PersonHive> results = em.createNativeQuery("select * from sparktest.IntermediatePerson").getResultList();
    matchResults(results, 4);
    sqlString = "INSERT INTO fs.[src/test/resources/testspark_csv] AS CSV FROM (select * from person)";
    q = em.createNativeQuery(sqlString, PersonHive.class);
    q.executeUpdate();
    sqlString = "INSERT INTO fs.[src/test/resources/testspark_json] AS JSON FROM (select * from person)";
    q = em.createNativeQuery(sqlString, PersonHive.class);
    q.executeUpdate();
}

60. SparkHiveQueryTest#testSaveIntermediateResult()

Project: Kundera
Source File: SparkHiveQueryTest.java
View license
/**
     * Test save intermediate result.
     */
private void testSaveIntermediateResult() {
    String sqlString = "INSERT INTO hive.sparktest.IntermediatePerson FROM (select * from person)";
    Query q = em.createNativeQuery(sqlString, PersonHive.class);
    q.executeUpdate();
    List<PersonHive> results = em.createNativeQuery("select * from sparktest.IntermediatePerson").getResultList();
    matchResults(results, 4);
    sqlString = "INSERT INTO fs.[src/test/resources/testspark_csv] AS CSV FROM (select * from person)";
    q = em.createNativeQuery(sqlString, PersonHive.class);
    q.executeUpdate();
    sqlString = "INSERT INTO fs.[src/test/resources/testspark_json] AS JSON FROM (select * from person)";
    q = em.createNativeQuery(sqlString, PersonHive.class);
    q.executeUpdate();
}

61. LOSSystemPropertyServiceBean#getByKey()

View license
public LOSSystemProperty getByKey(Client client, String workstation, String key) {
    if (client == null) {
        client = ctxService.getCallersClient();
    }
    if (workstation == null || workstation.length() == 0) {
        workstation = LOSSystemProperty.WORKSTATION_DEFAULT;
    }
    //		Query query = manager.createQuery(
    //							"SELECT sp FROM "+LOSSystemProperty.class.getSimpleName()+" sp "+
    //							"WHERE sp.key=:key and workstation=:workstation and client = :client");
    Query query = manager.createNamedQuery("LOSSystemProperty.queryByClientWorkstationKey");
    query.setParameter("key", key);
    query.setParameter("workstation", workstation);
    query.setParameter("client", client);
    try {
        return (LOSSystemProperty) query.getSingleResult();
    } catch (NoResultException ne) {
        return null;
    }
}

62. LocationFinderBean#existsDiffItem()

Project: myWMS
Source File: LocationFinderBean.java
View license
@SuppressWarnings("rawtypes")
private boolean existsDiffItem(LOSStorageLocation location, ItemData item) {
    StringBuilder sb = new StringBuilder();
    sb.append(" SELECT su.id FROM ");
    sb.append(StockUnit.class.getSimpleName() + " su, " + LOSUnitLoad.class.getSimpleName() + " ul ");
    sb.append(" WHERE ul.storageLocation=:location and su.unitLoad=ul and su.itemData != :item ");
    Query query = manager.createQuery(sb.toString());
    query.setParameter("location", location);
    query.setParameter("item", item);
    query.setMaxResults(1);
    List res = query.getResultList();
    return res.size() > 0;
}

63. StorageBusinessBean#getOpenStorageRequest()

Project: myWMS
Source File: StorageBusinessBean.java
View license
@SuppressWarnings("unchecked")
public LOSStorageRequest getOpenStorageRequest(String unitLoadLabel) {
    Query query = manager.createQuery("SELECT req FROM " + LOSStorageRequest.class.getSimpleName() + " req " + " WHERE req.unitLoad.labelId=:label " + " AND req.requestState in (:raw,:processing) ");
    query.setParameter("label", unitLoadLabel);
    query.setParameter("raw", LOSStorageRequestState.RAW);
    query.setParameter("processing", LOSStorageRequestState.PROCESSING);
    List<LOSStorageRequest> list = query.getResultList();
    if (list.size() > 0) {
        return list.get(0);
    }
    return null;
}

64. LOSGoodsReceiptServiceBean#getOpenByDeliveryNoteNumber()

View license
@Override
public LOSGoodsReceipt getOpenByDeliveryNoteNumber(String number) {
    Query query = manager.createQuery("SELECT gr FROM " + LOSGoodsReceipt.class.getSimpleName() + " gr " + "WHERE gr.deliveryNoteNumber=:n" + " AND receiptState in (:raw,:accepted)");
    query.setParameter("n", number);
    query.setParameter("raw", LOSGoodsReceiptState.RAW);
    query.setParameter("accepted", LOSGoodsReceiptState.ACCEPTED);
    try {
        return (LOSGoodsReceipt) query.getSingleResult();
    } catch (NoResultException nre) {
        return null;
    }
}

65. LOSWorkingAreaServiceBean#containsLocation()

View license
public boolean containsLocation(LOSWorkingArea area, LOSStorageLocation location) {
    LOSLocationCluster cluster = location.getCluster();
    if (cluster == null) {
        return false;
    }
    String queryStr = "SELECT o.id FROM " + LOSWorkingAreaPosition.class.getSimpleName() + " o WHERE o.workingArea=:area and o.cluster=:cluster";
    Query query = manager.createQuery(queryStr);
    query.setParameter("area", area);
    query.setParameter("cluster", cluster);
    query.setMaxResults(1);
    try {
        query.getSingleResult();
    } catch (NoResultException nre) {
        return false;
    }
    return true;
}

66. LOSStocktakingRecordServiceBean#getListByUnitLoadLabel()

View license
@SuppressWarnings("unchecked")
public List<LOSStocktakingRecord> getListByUnitLoadLabel(Client c, String unitLoadLabel) {
    Query query = manager.createQuery("SELECT sr FROM " + LOSStocktakingRecord.class.getSimpleName() + " sr " + " WHERE sr.client=:client" + " AND sr.unitLoadLabel = :label");
    query.setParameter("client", c);
    query.setParameter("label", unitLoadLabel);
    return query.getResultList();
}

67. ManufacturerDaoImpl#listByProductsByCategoriesId()

Project: shopizer
Source File: ManufacturerDaoImpl.java
View license
@SuppressWarnings("unchecked")
@Override
public List<Manufacturer> listByProductsByCategoriesId(MerchantStore store, List<Long> ids, Language language) {
    StringBuilder builderSelect = new StringBuilder();
    builderSelect.append("select distinct manufacturer from Product as p ");
    builderSelect.append("join p.manufacturer manufacturer ");
    builderSelect.append("join manufacturer.descriptions md ");
    builderSelect.append("join p.categories categs ");
    builderSelect.append("where categs.id in (:cid) ");
    builderSelect.append("and md.language.id=:lang");
    Query query = super.getEntityManager().createQuery(builderSelect.toString());
    query.setParameter("cid", ids);
    query.setParameter("lang", language.getId());
    return query.getResultList();
}

68. SecurityGroupManagerImpl#detachSecurityGroupFromL3Network()

View license
@Transactional
private void detachSecurityGroupFromL3Network(String sgUuid, String l3Uuid) {
    String sql = "select ref.uuid from VmNicSecurityGroupRefVO ref, VmNicVO nic where nic.uuid = ref.vmNicUuid and nic.l3NetworkUuid = :l3Uuid and ref.securityGroupUuid = :sgUuid";
    TypedQuery<String> tq = dbf.getEntityManager().createQuery(sql, String.class);
    tq.setParameter("l3Uuid", l3Uuid);
    tq.setParameter("sgUuid", sgUuid);
    List<String> refUuids = tq.getResultList();
    if (!refUuids.isEmpty()) {
        sql = "delete from VmNicSecurityGroupRefVO ref where ref.uuid in (:uuids)";
        Query q = dbf.getEntityManager().createQuery(sql);
        q.setParameter("uuids", refUuids);
        q.executeUpdate();
    }
    sql = "delete from SecurityGroupL3NetworkRefVO ref where ref.l3NetworkUuid = :l3Uuid and ref.securityGroupUuid = :sgUuid";
    Query q = dbf.getEntityManager().createQuery(sql);
    q.setParameter("l3Uuid", l3Uuid);
    q.setParameter("sgUuid", sgUuid);
    q.executeUpdate();
}

69. JpaStorage#getAllClientVersions()

Project: apiman
Source File: JpaStorage.java
View license
/**
     * @see io.apiman.manager.api.core.IStorage#getAllClientVersions(java.lang.String, java.lang.String)
     */
@Override
public Iterator<ClientVersionBean> getAllClientVersions(String organizationId, String clientId) throws StorageException {
    EntityManager entityManager = getActiveEntityManager();
    String jpql = "SELECT v " + "   FROM ClientVersionBean v " + "   JOIN v.client a " + "   JOIN a.organization o " + "  WHERE o.id = :orgId " + "    AND a.id = :clientId" + "  ORDER BY v.id ASC";
    Query query = entityManager.createQuery(jpql);
    query.setParameter("orgId", organizationId);
    query.setParameter("clientId", clientId);
    return super.getAll(ClientVersionBean.class, query);
}

70. JpaStorage#getAllPlanVersions()

Project: apiman
Source File: JpaStorage.java
View license
/**
     * @see io.apiman.manager.api.core.IStorage#getAllPlanVersions(java.lang.String, java.lang.String)
     */
@Override
public Iterator<PlanVersionBean> getAllPlanVersions(String organizationId, String planId) throws StorageException {
    EntityManager entityManager = getActiveEntityManager();
    String jpql = "SELECT v " + "   FROM PlanVersionBean v " + "   JOIN v.plan p " + "   JOIN p.organization o " + "  WHERE o.id = :orgId " + "    AND p.id = :planId" + "  ORDER BY v.id ASC";
    Query query = entityManager.createQuery(jpql);
    query.setParameter("orgId", organizationId);
    query.setParameter("planId", planId);
    return super.getAll(PlanVersionBean.class, query);
}

71. JpaStorage#getAllApiVersions()

Project: apiman
Source File: JpaStorage.java
View license
/**
     * @see io.apiman.manager.api.core.IStorage#getAllApiVersions(java.lang.String, java.lang.String)
     */
@Override
public Iterator<ApiVersionBean> getAllApiVersions(String organizationId, String apiId) throws StorageException {
    EntityManager entityManager = getActiveEntityManager();
    String jpql = "SELECT v " + "   FROM ApiVersionBean v " + "   JOIN v.api s " + "   JOIN s.organization o " + "  WHERE o.id = :orgId " + "    AND s.id = :apiId" + "  ORDER BY v.id ASC";
    Query query = entityManager.createQuery(jpql);
    query.setParameter("orgId", organizationId);
    query.setParameter("apiId", apiId);
    return super.getAll(ApiVersionBean.class, query);
}

72. JpaStorage#deleteAllAuditEntries()

Project: apiman
Source File: JpaStorage.java
View license
private void deleteAllAuditEntries(OrganizationBean organizationBean, AuditEntityType entityType, String entityId) throws StorageException {
    String jpql = "DELETE AuditEntryBean b " + " WHERE b.organizationId = :orgId ";
    if (entityId != null && entityType != null) {
        jpql += String.format("AND b.entityId = '%s' AND b.entityType = '%s' ", entityId, entityType.name());
    }
    Query query = getActiveEntityManager().createQuery(jpql);
    query.setParameter("orgId", organizationBean.getId());
    query.executeUpdate();
}

73. JpaStorage#deleteAllPlanVersions()

Project: apiman
Source File: JpaStorage.java
View license
private void deleteAllPlanVersions(OrganizationBean organizationBean) throws StorageException {
    String jpql = "DELETE PlanVersionBean deleteBean " + " WHERE deleteBean IN (" + "SELECT v" + "  FROM PlanVersionBean v " + "  JOIN v.plan p " + "  JOIN p.organization o " + " WHERE o.id = :orgId " + ")";
    Query query = getActiveEntityManager().createQuery(jpql);
    query.setParameter("orgId", organizationBean.getId());
    query.executeUpdate();
}

74. DatabaseNetwork#findByData()

Project: BotLibre
Source File: DatabaseNetwork.java
View license
/**
	 * Return the vertex with the given data.
	 */
public synchronized Vertex findByData(Object data) {
    if (data == null) {
        return null;
    }
    Vertex vertex = this.verticiesByData.get(data);
    if (vertex != null) {
        return vertex;
    }
    Query query = this.entityManager.createNamedQuery("findVertexByData");
    setHints(query);
    query.setParameter("data", BasicVertex.convertDataValue(data));
    query.setParameter("type", BasicVertex.convertDataType(data));
    try {
        vertex = (Vertex) query.getSingleResult();
        if (trackAccessCount()) {
            vertex.incrementAccessCount();
        }
        this.verticiesByData.put(vertex.getData(), vertex);
        return vertex;
    } catch (NoResultException notFound) {
        return null;
    }
}

75. StructuredContentDaoImpl#findStructuredContentTypeByName()

View license
@Override
public StructuredContentType findStructuredContentTypeByName(String name) {
    Query query = em.createNamedQuery("BC_READ_STRUCTURED_CONTENT_TYPE_BY_NAME");
    query.setParameter("name", name);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    List<StructuredContentType> results = query.getResultList();
    if (results.size() > 0) {
        return results.get(0);
    } else {
        return null;
    }
}

76. AdminNavigationDaoImpl#readAdminSectionByURI()

View license
@Override
public AdminSection readAdminSectionByURI(String uri) {
    Query query = em.createNamedQuery("BC_READ_ADMIN_SECTION_BY_URI");
    query.setParameter("uri", uri);
    query.setHint(org.hibernate.ejb.QueryHints.HINT_CACHEABLE, true);
    AdminSection adminSection = null;
    try {
        adminSection = (AdminSection) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return adminSection;
}

77. AdminNavigationDaoImpl#readAdminSectionBySectionKey()

View license
@Override
public AdminSection readAdminSectionBySectionKey(String sectionKey) {
    Query query = em.createNamedQuery("BC_READ_ADMIN_SECTION_BY_SECTION_KEY");
    query.setHint(org.hibernate.ejb.QueryHints.HINT_CACHEABLE, true);
    query.setParameter("sectionKey", sectionKey);
    AdminSection adminSection = null;
    try {
        adminSection = (AdminSection) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return adminSection;
}

78. LocaleDaoImpl#findLocaleByCode()

View license
/**
     * @return The locale for the passed in code
     */
@Override
public Locale findLocaleByCode(String localeCode) {
    Query query = em.createNamedQuery("BC_READ_LOCALE_BY_CODE");
    query.setParameter("localeCode", localeCode);
    query.setHint(org.hibernate.ejb.QueryHints.HINT_CACHEABLE, true);
    List<Locale> localeList = (List<Locale>) query.getResultList();
    if (localeList.size() >= 1) {
        if (localeList.size() > 1) {
            LOG.warn("Locale code " + localeCode + " exists for more than one locale");
        }
        return localeList.get(0);
    }
    return null;
}

79. ReviewDetailDaoImpl#readReviewByCustomerAndItem()

View license
@Override
public ReviewDetail readReviewByCustomerAndItem(Customer customer, String itemId) {
    final Query query = em.createNamedQuery("BC_READ_REVIEW_DETAIL_BY_CUSTOMER_ID_AND_ITEM_ID");
    query.setParameter("customerId", customer.getId());
    query.setParameter("itemId", itemId);
    ReviewDetail reviewDetail = null;
    try {
        reviewDetail = (ReviewDetail) query.getSingleResult();
    } catch (NoResultException nre) {
    }
    return reviewDetail;
}

80. StructuredContentDaoImpl#findStructuredContentTypeByName()

View license
@Override
public StructuredContentType findStructuredContentTypeByName(String name) {
    Query query = em.createNamedQuery("BC_READ_STRUCTURED_CONTENT_TYPE_BY_NAME");
    query.setParameter("name", name);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    List<StructuredContentType> results = query.getResultList();
    if (results.size() > 0) {
        return results.get(0);
    } else {
        return null;
    }
}

81. AdminNavigationDaoImpl#readAdminSectionByURI()

View license
@Override
public AdminSection readAdminSectionByURI(String uri) {
    Query query = em.createNamedQuery("BC_READ_ADMIN_SECTION_BY_URI");
    query.setParameter("uri", uri);
    query.setHint(org.hibernate.ejb.QueryHints.HINT_CACHEABLE, true);
    AdminSection adminSection = null;
    try {
        adminSection = (AdminSection) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return adminSection;
}

82. AdminNavigationDaoImpl#readAdminSectionBySectionKey()

View license
@Override
public AdminSection readAdminSectionBySectionKey(String sectionKey) {
    Query query = em.createNamedQuery("BC_READ_ADMIN_SECTION_BY_SECTION_KEY");
    query.setHint(org.hibernate.ejb.QueryHints.HINT_CACHEABLE, true);
    query.setParameter("sectionKey", sectionKey);
    AdminSection adminSection = null;
    try {
        adminSection = (AdminSection) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return adminSection;
}

83. LocaleDaoImpl#findLocaleByCode()

Project: broadleaf_modify
Source File: LocaleDaoImpl.java
View license
/**
     * @return The locale for the passed in code
     */
@Override
public Locale findLocaleByCode(String localeCode) {
    Query query = em.createNamedQuery("BC_READ_LOCALE_BY_CODE");
    query.setParameter("localeCode", localeCode);
    query.setHint(org.hibernate.ejb.QueryHints.HINT_CACHEABLE, true);
    List<Locale> localeList = (List<Locale>) query.getResultList();
    if (localeList.size() >= 1) {
        if (localeList.size() > 1) {
            LOG.warn("Locale code " + localeCode + " exists for more than one locale");
        }
        return localeList.get(0);
    }
    return null;
}

84. ReviewDetailDaoImpl#readReviewByCustomerAndItem()

View license
@Override
public ReviewDetail readReviewByCustomerAndItem(Customer customer, String itemId) {
    final Query query = em.createNamedQuery("BC_READ_REVIEW_DETAIL_BY_CUSTOMER_ID_AND_ITEM_ID");
    query.setParameter("customerId", customer.getId());
    query.setParameter("itemId", itemId);
    ReviewDetail reviewDetail = null;
    try {
        reviewDetail = (ReviewDetail) query.getSingleResult();
    } catch (NoResultException nre) {
    }
    return reviewDetail;
}

85. DatasetServiceBean#getDatasetVersionUser()

Project: dataverse
Source File: DatasetServiceBean.java
View license
public DatasetVersionUser getDatasetVersionUser(DatasetVersion version, User user) {
    DatasetVersionUser ddu = null;
    Query query = em.createQuery("select object(o) from DatasetVersionUser as o " + "where o.datasetVersion.id =:versionId and o.authenticatedUser.id =:userId");
    query.setParameter("versionId", version.getId());
    String identifier = user.getIdentifier();
    identifier = identifier.startsWith("@") ? identifier.substring(1) : identifier;
    AuthenticatedUser au = authentication.getAuthenticatedUser(identifier);
    query.setParameter("userId", au.getId());
    try {
        ddu = (DatasetVersionUser) query.getSingleResult();
    } catch (javax.persistence.NoResultException e) {
    }
    return ddu;
}

86. DataverseFieldTypeInputLevelServiceBean#findByDataverseIdAndDatasetFieldTypeIdList()

View license
/**
     * Find a list of DataverseFieldTypeInputLevel objects
     *  Search criteria: 
     *      - Dataverse Id, 
     *      - list of DatasetField Ids
     * 
     * @param dataverseId
     * @param datasetFieldIdList
     * @return List of DataverseFieldTypeInputLevel
     */
public List<DataverseFieldTypeInputLevel> findByDataverseIdAndDatasetFieldTypeIdList(Long dataverseId, List<Long> datasetFieldIdList) {
    msg("---- findByDataverseIdAndDatasetFieldTypeIdList ----");
    if (datasetFieldIdList == null || datasetFieldIdList.size() == 0) {
        return null;
    }
    if (dataverseId == null) {
        return null;
    }
    Query query = em.createNamedQuery("DataverseFieldTypeInputLevel.findByDataverseIdAndDatasetFieldTypeIdList", DataverseFieldTypeInputLevel.class);
    query.setParameter("datasetFieldIdList", datasetFieldIdList);
    query.setParameter("dataverseId", dataverseId);
    try {
        return query.getResultList();
    /*List res = query.getResultList();
            msg("Number of results: " + res.size());
            return res;*/
    } catch (NoResultException nre) {
        return null;
    }
}

87. MonitoringJdbcStateStore#deletePendingInstances()

View license
public void deletePendingInstances(String feedName, String clusterName) {
    EntityManager entityManager = getEntityManager();
    beginTransaction(entityManager);
    Query q = entityManager.createNamedQuery(PersistenceConstants.DELETE_ALL_INSTANCES_FOR_FEED);
    q.setParameter("feedName", feedName);
    q.setParameter("clusterName", clusterName);
    try {
        q.executeUpdate();
    } finally {
        commitAndCloseTransaction(entityManager);
    }
}

88. JDBCStateStore#deleteEntity()

Project: falcon
Source File: JDBCStateStore.java
View license
@Override
public void deleteEntity(EntityID entityID) throws StateStoreException {
    if (!entityExists(entityID)) {
        throw new StateStoreException("Entity with key, " + entityID.getKey() + " does not exist.");
    }
    EntityManager entityManager = getEntityManager();
    beginTransaction(entityManager);
    Query q = entityManager.createNamedQuery(PersistenceConstants.DELETE_ENTITY);
    q.setParameter("id", entityID.getKey());
    q.executeUpdate();
    commitAndCloseTransaction(entityManager);
}

89. JDBCStateStore#getAllExecutionInstances()

Project: falcon
Source File: JDBCStateStore.java
View license
@Override
public Collection<InstanceState> getAllExecutionInstances(Entity entity, String cluster) throws StateStoreException {
    EntityClusterID id = new EntityClusterID(entity, cluster);
    EntityManager entityManager = getEntityManager();
    Query q = entityManager.createNamedQuery(PersistenceConstants.GET_INSTANCES_FOR_ENTITY_CLUSTER);
    q.setParameter("entityId", id.getEntityID().getKey());
    q.setParameter("cluster", cluster);
    List result = q.getResultList();
    entityManager.close();
    try {
        return BeanMapperUtil.convertToInstanceState(result);
    } catch (IOException e) {
        throw new StateStoreException(e);
    }
}

90. JDBCStateStore#getExecutionInstances()

Project: falcon
Source File: JDBCStateStore.java
View license
@Override
public Collection<InstanceState> getExecutionInstances(EntityClusterID id, Collection<InstanceState.STATE> states) throws StateStoreException {
    String entityKey = id.getEntityID().getKey();
    EntityManager entityManager = getEntityManager();
    Query q = entityManager.createNamedQuery(PersistenceConstants.GET_INSTANCES_FOR_ENTITY_FOR_STATES);
    q.setParameter("entityId", entityKey);
    List<String> instanceStates = new ArrayList<>();
    for (InstanceState.STATE state : states) {
        instanceStates.add(state.toString());
    }
    q.setParameter("currentState", instanceStates);
    List result = q.getResultList();
    entityManager.close();
    try {
        return BeanMapperUtil.convertToInstanceState(result);
    } catch (IOException e) {
        throw new StateStoreException(e);
    }
}

91. JDBCStateStore#deleteExecutionInstance()

Project: falcon
Source File: JDBCStateStore.java
View license
@Override
public void deleteExecutionInstance(InstanceID instanceID) throws StateStoreException {
    String instanceKey = instanceID.toString();
    if (!executionInstanceExists(instanceID)) {
        throw new StateStoreException("Instance with key, " + instanceKey + " does not exist.");
    }
    EntityManager entityManager = getEntityManager();
    beginTransaction(entityManager);
    Query q = entityManager.createNamedQuery(PersistenceConstants.DELETE_INSTANCE);
    q.setParameter("id", instanceKey);
    q.executeUpdate();
    commitAndCloseTransaction(entityManager);
}

92. JpaProcessPersistenceContext#getProcessInstanceByCorrelationKey()

View license
/**
     * With regards to locking, the method is not always called during a transaction, which means 
     * that including logic to lock the query will cause exceptions and is not feasible. 
     * </p>
     * However, this is not an issue: see the {@link #getProcessInstancesWaitingForEvent(String)} documentation
     * for more information. The same logic applies to this method. 
     * </p>
     */
public Long getProcessInstanceByCorrelationKey(CorrelationKey correlationKey) {
    Query processInstancesForEvent = getEntityManager().createNamedQuery("GetProcessInstanceIdByCorrelation");
    processInstancesForEvent.setParameter("elem_count", new Long(correlationKey.getProperties().size()));
    List<Object> properties = new ArrayList<Object>();
    for (CorrelationProperty<?> property : correlationKey.getProperties()) {
        properties.add(property.getValue());
    }
    processInstancesForEvent.setParameter("properties", properties);
    try {
        return (Long) processInstancesForEvent.getSingleResult();
    } catch (NonUniqueResultException e) {
        return null;
    } catch (NoResultException e) {
        return null;
    }
}

93. CorrelationPersistenceTest#testCreateCorrelation()

View license
@Test
public void testCreateCorrelation() throws Exception {
    EntityManagerFactory emf = (EntityManagerFactory) context.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
    EntityManager em = emf.createEntityManager();
    Query query = em.createNamedQuery("GetProcessInstanceIdByCorrelation");
    query.setParameter("properties", Arrays.asList(new String[] { "test123" }));
    query.setParameter("elem_count", new Long(1));
    List<Long> processInstances = query.getResultList();
    em.close();
    assertNotNull(processInstances);
    assertEquals(1, processInstances.size());
}

94. CorrelationPersistenceTest#testCreateCorrelationMultiValueDoesNotMatch()

View license
@Test
public void testCreateCorrelationMultiValueDoesNotMatch() throws Exception {
    EntityManagerFactory emf = (EntityManagerFactory) context.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
    EntityManager em = emf.createEntityManager();
    Query query = em.createNamedQuery("GetProcessInstanceIdByCorrelation");
    query.setParameter("properties", Arrays.asList(new String[] { "test123" }));
    query.setParameter("elem_count", new Long(2));
    List<Long> processInstances = query.getResultList();
    em.close();
    assertNotNull(processInstances);
    assertEquals(0, processInstances.size());
}

95. CorrelationPersistenceTest#testCreateCorrelationMultiValueDoesMatch()

View license
@Test
public void testCreateCorrelationMultiValueDoesMatch() throws Exception {
    EntityManagerFactory emf = (EntityManagerFactory) context.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
    EntityManager em = emf.createEntityManager();
    Query query = em.createNamedQuery("GetProcessInstanceIdByCorrelation");
    query.setParameter("properties", Arrays.asList(new String[] { "test123", "123test" }));
    query.setParameter("elem_count", new Long(2));
    List<Long> processInstances = query.getResultList();
    em.close();
    assertNotNull(processInstances);
    assertEquals(1, processInstances.size());
}

96. JPAMapper#getProcessInstanceByCorrelationKey()

Project: jbpm
Source File: JPAMapper.java
View license
public Context getProcessInstanceByCorrelationKey(CorrelationKey correlationKey, EntityManager em) {
    Query processInstancesForEvent = em.createNamedQuery("GetProcessInstanceIdByCorrelation");
    processInstancesForEvent.setParameter("elem_count", new Long(correlationKey.getProperties().size()));
    List<Object> properties = new ArrayList<Object>();
    for (CorrelationProperty<?> property : correlationKey.getProperties()) {
        properties.add(property.getValue());
    }
    processInstancesForEvent.setParameter("properties", properties);
    try {
        return ProcessInstanceIdContext.get((Long) processInstancesForEvent.getSingleResult());
    } catch (NonUniqueResultException e) {
        return null;
    } catch (NoResultException e) {
        return null;
    }
}

97. AlbumService#create()

Project: keycloak
Source File: AlbumService.java
View license
@POST
@Consumes("application/json")
public Response create(Album newAlbum) {
    Principal userPrincipal = request.getUserPrincipal();
    newAlbum.setUserId(userPrincipal.getName());
    Query queryDuplicatedAlbum = this.entityManager.createQuery("from Album where name = :name and userId = :userId");
    queryDuplicatedAlbum.setParameter("name", newAlbum.getName());
    queryDuplicatedAlbum.setParameter("userId", userPrincipal.getName());
    if (!queryDuplicatedAlbum.getResultList().isEmpty()) {
        throw new ErrorResponse("Name [" + newAlbum.getName() + "] already taken. Choose another one.", Status.CONFLICT);
    }
    this.entityManager.persist(newAlbum);
    createProtectedResource(newAlbum);
    return Response.ok(newAlbum).build();
}

98. JPAResourceStore#findByName()

Project: keycloak
Source File: JPAResourceStore.java
View license
@Override
public Resource findByName(String name, String resourceServerId) {
    Query query = entityManager.createQuery("from ResourceEntity where resourceServer.id = :serverId and name = :name");
    query.setParameter("serverId", resourceServerId);
    query.setParameter("name", name);
    List<Resource> result = query.getResultList();
    if (!result.isEmpty()) {
        return result.get(0);
    }
    return null;
}

99. AlbumService#create()

Project: keycloak
Source File: AlbumService.java
View license
@POST
@Consumes("application/json")
public Response create(Album newAlbum) {
    Principal userPrincipal = request.getUserPrincipal();
    newAlbum.setUserId(userPrincipal.getName());
    Query queryDuplicatedAlbum = this.entityManager.createQuery("from Album where name = :name and userId = :userId");
    queryDuplicatedAlbum.setParameter("name", newAlbum.getName());
    queryDuplicatedAlbum.setParameter("userId", userPrincipal.getName());
    if (!queryDuplicatedAlbum.getResultList().isEmpty()) {
        throw new ErrorResponse("Name [" + newAlbum.getName() + "] already taken. Choose another one.", Status.CONFLICT);
    }
    this.entityManager.persist(newAlbum);
    createProtectedResource(newAlbum);
    return Response.ok(newAlbum).build();
}

100. CassandraNativeFunctionsTest#testUserDefinedFunctions()

View license
/**
     * Test user defined functions.
     */
@Test
public void testUserDefinedFunctions() {
    String useNativeSql = "USE " + "\"KunderaExamples\"";
    Query q = entityManager.createNativeQuery(useNativeSql);
    q.executeUpdate();
    // create user defined function
    String udf = "CREATE OR REPLACE FUNCTION fLog (input int) " + "CALLED ON NULL INPUT " + "RETURNS double " + "LANGUAGE java AS 'return Double.valueOf(Math.log(input.intValue()));'";
    q = entityManager.createNativeQuery(udf);
    q.executeUpdate();
    // Assert values
    String qry = "Select fLog(\"AGE\") from \"PERSONCASSANDRA\" where \"personId\" = '1'";
    q = entityManager.createNativeQuery(qry);
    List persons = q.getResultList();
    Assert.assertNotNull(persons);
    Assert.assertFalse(persons.isEmpty());
    Assert.assertEquals(1, persons.size());
    // log 10 base e
    Assert.assertEquals(2.302585092994046, ((Map) persons.get(0)).get("KunderaExamples.flog(AGE)"));
}