javax.persistence.Query

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

1. 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());
}

2. 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();
}

3. 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;
}

4. 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();
}

5. 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;
}

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. 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();
}

17. 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();
}

18. 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());
}

19. 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();
}

20. 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;
    }
}

21. 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());
}

22. 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);
}

23. 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);
}

24. 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);
}

25. 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();
}

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: 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;
}

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. 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();
}

34. 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;
    }
}

35. 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();
}

36. 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;
}

37. 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;
}

38. 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;
}

39. 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;
}

40. 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;
    }
}

41. 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());
}

42. 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());
}

43. 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());
}

44. 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"));
    }
}

45. 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;
}

46. 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;
}

47. 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;
    }
}

48. 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();
}

49. 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();
}

50. 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();
}

51. 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();
}

52. 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();
}

53. 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();
}

54. 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();
}

55. 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;
    }
}

56. 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();
}

57. 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();
}

58. 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;
}

59. 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;
}

60. 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);
    }
}

61. 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);
    }
}

62. 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);
    }
}

63. 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);
    }
}

64. 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;
    }
}

65. 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;
    }
}

66. 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;
    }
}

67. 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();
}

68. 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);
}

69. RedisMappedSuperClassTest#tearDown()

View license
@After
public void tearDown() throws Exception {
    // Delete by query.
    String deleteQuery = "Delete from CreditTransaction p";
    Query query = em.createQuery(deleteQuery);
    query.executeUpdate();
    deleteQuery = "Delete from DebitTransaction p";
    query = em.createQuery(deleteQuery);
    query.executeUpdate();
    tearDownInternal();
}

70. OracleToMongoJTATest#tearDown()

Project: Kundera
Source File: OracleToMongoJTATest.java
View license
/**
     * @throws java.lang.Exception
     */
@After
public void tearDown() throws Exception {
    userTransaction.begin();
    // Delete by query.
    String deleteQuery = "Delete from OraclePersonnelOTOFKEntityJTA p";
    Query query = em.createQuery(deleteQuery);
    query.executeUpdate();
    deleteQuery = "Delete from HabitatOToOFKEntityJTA p";
    query = em.createQuery(deleteQuery);
    query.executeUpdate();
    userTransaction.commit();
    initialContext.unbind("java:comp/UserTransaction");
    initialContext.destroySubcontext("java:comp");
}

71. LOSJasperReportServiceBean#getByName()

View license
public LOSJasperReport getByName(Client client, String name) {
    if (client == null) {
        client = clientService.getSystemClient();
    }
    StringBuffer b = new StringBuffer();
    b.append("SELECT des FROM ");
    b.append(LOSJasperReport.class.getSimpleName());
    b.append(" des ");
    b.append(" WHERE name=:name and client=:client ");
    Query query = manager.createQuery(new String(b));
    query.setParameter("name", name);
    query.setParameter("client", client);
    try {
        return (LOSJasperReport) query.getSingleResult();
    } catch (NoResultException e) {
    }
    return null;
}

72. LocationFinderBean#existsClientLocations()

Project: myWMS
Source File: LocationFinderBean.java
View license
@SuppressWarnings("rawtypes")
private boolean existsClientLocations(Client client) {
    StringBuilder sb = new StringBuilder();
    sb.append(" SELECT name FROM ");
    sb.append(LOSStorageLocation.class.getSimpleName() + " loc ");
    sb.append(" WHERE client = :client ");
    Query query = manager.createQuery(sb.toString());
    query.setParameter("client", client);
    query.setMaxResults(1);
    List res = query.getResultList();
    return res.size() > 0;
}

73. LOSExtinguishFacadeBean#getListByLot()

Project: myWMS
Source File: LOSExtinguishFacadeBean.java
View license
@SuppressWarnings("unchecked")
public List<StockUnit> getListByLot(Lot lot, boolean checkAvailable) {
    LOSStorageLocation nirwana = locationService.getNirwana();
    StringBuffer qstr = new StringBuffer();
    qstr.append("SELECT su FROM " + StockUnit.class.getSimpleName() + " su, ");
    qstr.append(LOSUnitLoad.class.getSimpleName() + " ul ");
    qstr.append("WHERE su.unitLoad = ul AND su.lot = :lot ");
    qstr.append(" AND su.lock != " + StockUnitLockState.PICKED_FOR_GOODSOUT.getLock());
    ;
    qstr.append(" AND su.lock != " + BusinessObjectLockState.GOING_TO_DELETE.getLock());
    ;
    qstr.append(" AND (su.amount-su.reservedAmount) > 0");
    qstr.append(" AND ul.storageLocation != :nirwana");
    Query query = manager.createQuery(qstr.toString());
    query.setParameter("lot", lot);
    query.setParameter("nirwana", nirwana);
    return (List<StockUnit>) query.getResultList();
}

74. LOSBomServiceBean#getBom()

Project: myWMS
Source File: LOSBomServiceBean.java
View license
@SuppressWarnings("unchecked")
public LOSBom getBom(ItemData parent, ItemData child) {
    String queryStr = "SELECT bom FROM " + LOSBom.class.getSimpleName() + " bom WHERE bom.parent = :parent and bom.child = :child ";
    Query query = manager.createQuery(queryStr);
    query.setParameter("parent", parent);
    query.setParameter("child", child);
    List<LOSBom> posList = null;
    try {
        posList = query.getResultList();
    } catch (NoResultException ex) {
    }
    return (posList != null && posList.size() > 0) ? posList.get(0) : null;
}

75. LOSCustomerOrderServiceBean#getByExternalId()

View license
@SuppressWarnings("unchecked")
public List<LOSCustomerOrder> getByExternalId(Client client, String externalId) {
    String queryStr = "SELECT o FROM " + LOSCustomerOrder.class.getSimpleName() + " o " + "WHERE o.externalId=:externalId";
    if (client != null) {
        queryStr += " and client=:client";
    }
    Query query = manager.createQuery(queryStr);
    query.setParameter("externalId", externalId);
    if (client != null) {
        query.setParameter("client", client);
    }
    return query.getResultList();
}

76. LOSCustomerOrderServiceBean#getByExternalNumber()

View license
@SuppressWarnings("unchecked")
public List<LOSCustomerOrder> getByExternalNumber(Client client, String externalNumber) {
    String queryStr = "SELECT o FROM " + LOSCustomerOrder.class.getSimpleName() + " o " + "WHERE o.externalNumber=:externalNumber";
    if (client != null) {
        queryStr += " and client=:client";
    }
    Query query = manager.createQuery(queryStr);
    query.setParameter("externalNumber", externalNumber);
    if (client != null) {
        query.setParameter("client", client);
    }
    return query.getResultList();
}

77. LOSOrderStrategyServiceBean#getByName()

View license
public LOSOrderStrategy getByName(Client client, String name) {
    if (client == null) {
        client = contextService.getCallersClient();
    }
    String queryStr = "SELECT o FROM " + LOSOrderStrategy.class.getSimpleName() + " o " + "WHERE o.name=:name and client=:client";
    Query query = manager.createQuery(queryStr);
    query.setParameter("name", name);
    query.setParameter("client", client);
    try {
        return (LOSOrderStrategy) query.getSingleResult();
    } catch (NoResultException ne) {
        if (!client.isSystemClient()) {
            return getByName(clientService.getSystemClient(), name);
        }
    }
    return null;
}

78. LOSPickingOrderServiceBean#getByCustomerOrderNumber()

View license
@SuppressWarnings("unchecked")
public List<LOSPickingOrder> getByCustomerOrderNumber(String customerOrderNumber) {
    StringBuilder b = new StringBuilder();
    b.append("SELECT po FROM ");
    b.append(LOSPickingOrder.class.getSimpleName());
    b.append(" po ");
    b.append(" WHERE po.customerOrderNumber=:number ");
    Query query = manager.createQuery(new String(b));
    query.setParameter("number", customerOrderNumber);
    return query.getResultList();
}

79. LOSPickingPositionServiceBean#getByPickFromStockUnit()

View license
@SuppressWarnings("unchecked")
public List<LOSPickingPosition> getByPickFromStockUnit(StockUnit pickFromStockUnit) {
    StringBuffer b = new StringBuffer();
    Query query;
    b.append(" SELECT pos FROM ");
    b.append(LOSPickingPosition.class.getName());
    b.append(" pos ");
    b.append(" WHERE pos.pickFromStockUnit=:su");
    b.append(" ORDER BY pos.id ");
    query = manager.createQuery(new String(b));
    query.setParameter("su", pickFromStockUnit);
    return query.getResultList();
}

80. LOSPickingPositionServiceBean#getByPickFromUnitLoadLabel()

View license
@SuppressWarnings("unchecked")
public List<LOSPickingPosition> getByPickFromUnitLoadLabel(String label) {
    StringBuffer b = new StringBuffer();
    Query query;
    b = new StringBuffer();
    b.append(" SELECT pos FROM ");
    b.append(LOSPickingPosition.class.getName());
    b.append(" pos ");
    b.append(" WHERE pos.pickFromUnitLoadLabel=:label");
    b.append(" ORDER BY pos.id ");
    query = manager.createQuery(new String(b));
    query.setParameter("label", label);
    return query.getResultList();
}

81. LOSPickingPositionServiceBean#getByPickToUnitLoad()

View license
@SuppressWarnings("unchecked")
public List<LOSPickingPosition> getByPickToUnitLoad(LOSPickingUnitLoad pickToUnitLoad) {
    StringBuffer b = new StringBuffer();
    Query query;
    b.append(" SELECT pos FROM ");
    b.append(LOSPickingPosition.class.getName());
    b.append(" pos ");
    b.append(" WHERE pos.pickToUnitLoad=:pickToUnitLoad");
    b.append(" ORDER BY pos.id ");
    query = manager.createQuery(new String(b));
    query.setParameter("pickToUnitLoad", pickToUnitLoad);
    return query.getResultList();
}

82. LOSPickingPositionServiceBean#getByCustomerOrderNumber()

View license
@SuppressWarnings("unchecked")
public List<LOSPickingPosition> getByCustomerOrderNumber(String orderNumber) {
    StringBuffer b = new StringBuffer();
    Query query;
    b.append(" SELECT pos FROM ");
    b.append(LOSPickingPosition.class.getName());
    b.append(" pos ");
    b.append(" WHERE pos.customerOrderPosition.order.number=:orderNumber");
    b.append(" ORDER BY pos.customerOrderPosition.index, pos.id ");
    query = manager.createQuery(new String(b));
    query.setParameter("orderNumber", orderNumber);
    return query.getResultList();
}

83. QueryLotServiceBean#getByNameAndItemData()

Project: myWMS
Source File: QueryLotServiceBean.java
View license
public Lot getByNameAndItemData(String name, ItemData item) {
    StringBuffer sb = new StringBuffer("SELECT l FROM ");
    sb.append(Lot.class.getSimpleName() + " l ");
    sb.append("WHERE l.name=:na ");
    sb.append("AND l.itemData=:it");
    Query query = manager.createQuery(sb.toString());
    query.setParameter("na", name);
    query.setParameter("it", item);
    try {
        return (Lot) query.getSingleResult();
    } catch (NoResultException ex) {
        return null;
    }
}

84. LOSRackServiceBean#getByName()

Project: myWMS
Source File: LOSRackServiceBean.java
View license
//------------------------------------------------------------------------
public LOSRack getByName(Client client, String name) throws EntityNotFoundException {
    Query query = manager.createQuery("SELECT r FROM " + LOSRack.class.getSimpleName() + " r " + "WHERE r.name=:name " + "AND r.client=:cl");
    query.setParameter("name", name);
    query.setParameter("cl", client);
    try {
        LOSRack r = (LOSRack) query.getSingleResult();
        return r;
    } catch (NoResultException ex) {
        throw new EntityNotFoundException(ServiceExceptionKey.NO_ENTITY_WITH_NAME);
    }
}

85. LOSUnitLoadServiceBean#existsByStorageLocation()

Project: myWMS
Source File: LOSUnitLoadServiceBean.java
View license
//-----------------------------------------------------------------------
public boolean existsByStorageLocation(LOSStorageLocation location) {
    Query query = manager.createNamedQuery("LOSUnitLoad.existsByLocation");
    query.setParameter("location", location);
    query.setMaxResults(1);
    try {
        query.getSingleResult();
    } catch (NoResultException nre) {
        return false;
    }
    return true;
}

86. LOSUnitLoadServiceBean#hasOtherChilds()

Project: myWMS
Source File: LOSUnitLoadServiceBean.java
View license
public boolean hasOtherChilds(LOSUnitLoad unitLoad, LOSUnitLoad notOther) {
    if (unitLoad == null) {
        return false;
    }
    String queryStr = "SELECT ul.id FROM " + LOSUnitLoad.class.getSimpleName() + " ul WHERE ul.carrierUnitLoadId = :id AND ul!=:notOther";
    Query query = manager.createQuery(queryStr);
    query.setParameter("id", unitLoad.getId());
    query.setParameter("notOther", notOther);
    try {
        query.getSingleResult();
    } catch (NoResultException nre) {
        return false;
    } catch (Throwable t) {
    }
    return true;
}

87. LOSStorageReportFacadeBean#autocompleteClientName()

View license
//--------------------------------------------------------------------------------
@SuppressWarnings("unchecked")
public List<String> autocompleteClientName(String namepart) {
    String lower = namepart.toLowerCase();
    Query query = manager.createQuery("SELECT cl.name FROM " + Client.class.getSimpleName() + " cl " + "WHERE LOWER(cl.name) LIKE :cln");
    query.setParameter("cln", lower + "%");
    return query.getResultList();
}

88. QueryFixedAssignmentServiceBean#existsByItemData()

View license
public boolean existsByItemData(ItemData item) {
    Query query = manager.createNamedQuery("LOSFixedLocationAssignment.existsByItem");
    query.setParameter("item", item);
    query.setMaxResults(1);
    try {
        query.getSingleResult();
    } catch (NoResultException nre) {
        return false;
    }
    return true;
}

89. QueryFixedAssignmentServiceBean#existsByLocation()

View license
public boolean existsByLocation(LOSStorageLocation location) {
    Query query = manager.createNamedQuery("LOSFixedLocationAssignment.existsByLocation");
    query.setParameter("location", location);
    query.setMaxResults(1);
    try {
        query.getSingleResult();
    } catch (NoResultException nre) {
        return false;
    }
    return true;
}

90. QueryTypeCapacityConstraintServiceBean#getListByLocationType()

View license
/*
	 * (non-Javadoc)
	 * @see de.linogistix.los.location.service.QueryTypeCapacityConstraintService#getListByLocationType(de.linogistix.los.location.model.LOSStorageLocationType)
	 */
@SuppressWarnings("unchecked")
public List<LOSTypeCapacityConstraint> getListByLocationType(LOSStorageLocationType slType) {
    StringBuffer sb = new StringBuffer("SELECT tcc FROM ");
    sb.append(LOSTypeCapacityConstraint.class.getSimpleName() + " tcc ");
    sb.append("WHERE tcc.storageLocationType=:slt");
    Query query = manager.createQuery(sb.toString());
    query.setParameter("slt", slType);
    return query.getResultList();
}

91. AreaServiceBean#getByName()

Project: myWMS
Source File: AreaServiceBean.java
View license
/**
     * @see org.mywms.service.AreaService#getByNameClient, String)
     */
public Area getByName(Client client, String name) throws EntityNotFoundException {
    Query query = manager.createQuery("SELECT ar FROM " + Area.class.getSimpleName() + " ar " + "WHERE ar.name=:name " + "AND ar.client=:cl");
    query.setParameter("name", name);
    query.setParameter("cl", client);
    try {
        Area area = (Area) query.getSingleResult();
        return area;
    } catch (NoResultException ex) {
        throw new EntityNotFoundException(ServiceExceptionKey.NO_AREA_WITH_NAME);
    }
}

92. ItemDataServiceBean#getByItemNumber()

Project: myWMS
Source File: ItemDataServiceBean.java
View license
/**
     * @see org.mywms.service.ItemDataService#getByItemNumber(Client,
     *      java.lang.String)
     */
public ItemData getByItemNumber(Client client, String itemNumber) {
    Query query = manager.createQuery("SELECT id FROM " + ItemData.class.getSimpleName() + " id " + "WHERE id.number=:itemNumber " + "AND id.client=:cl");
    query.setParameter("itemNumber", itemNumber);
    query.setParameter("cl", client);
    try {
        ItemData id = (ItemData) query.getSingleResult();
        return id;
    } catch (NoResultException ex) {
        return null;
    }
}

93. IMDBJPAQueriesTest#findMoviesBetweenAPeriod()

Project: Kundera
Source File: IMDBJPAQueriesTest.java
View license
private void findMoviesBetweenAPeriod() {
    // Between
    Query query = em.createQuery("select m from Movie m where m.year between :start AND :end");
    query.setParameter("start", 1990);
    query.setParameter("end", 2006);
    List<Movie> movies = query.getResultList();
    Assert.assertNotNull(movies);
    Assert.assertFalse(movies.isEmpty());
    Assert.assertEquals(2, movies.size());
}

94. LikeQueryTest#likeQueryTest()

Project: Kundera
Source File: LikeQueryTest.java
View license
/**
     * Like query test.
     */
@Test
public void likeQueryTest() {
    init();
    em.clear();
    String qry = "Select p from HBasePerson p where p.personName like :name";
    Query q = em.createQuery(qry);
    q.setParameter("name", "pragal");
    List<HBasePerson> persons = q.getResultList();
    assertNotNull(persons);
    Assert.assertEquals(1, persons.size());
    Assert.assertEquals("pragalbh garg", persons.get(0).getPersonName());
    qry = "Select p from HBasePerson p where p.personName like :name";
    q = em.createQuery(qry);
    q.setParameter("name", "thik");
    persons = q.getResultList();
    assertEquals(1, persons.size());
    assertEquals("karthik prasad", persons.get(0).getPersonName());
}

95. UserInfoTest#deleteNamed()

Project: Kundera
Source File: UserInfoTest.java
View license
/**
     * 
     */
private void deleteNamed() {
    UUID timeLineId = UUID.randomUUID();
    Date currentDate = new Date();
    MongoCompoundKey key = new MongoCompoundKey("mevivs", 1, timeLineId);
    String deleteQuery = "Delete From UserInfo u where u.firstName= :firstName";
    EntityManager em = emf.createEntityManager();
    Query q = em.createQuery(deleteQuery);
    q.setParameter("firstName", "Kuldeep");
    q.executeUpdate();
    UserInfo result = em.find(UserInfo.class, "mevivs_info");
    Assert.assertNull(result);
    em.close();
}

96. MongoCompositeTypeTest#onQuery()

Project: Kundera
Source File: MongoCompositeTypeTest.java
View license
@Test
public synchronized void onQuery() {
    EntityManager em = emf.createEntityManager();
    UUID timeLineId = UUID.randomUUID();
    MongoCompoundKey key = new MongoCompoundKey("mevivs", 1, timeLineId);
    MongoPrimeUser user = new MongoPrimeUser(key);
    user.setTweetBody("my first tweet");
    user.setTweetDate(currentDate);
    em.persist(user);
    // optional,just to clear persistence cache.
    em.close();
    em = emf.createEntityManager();
    final String noClause = "Select u from MongoPrimeUser u";
    final String withFirstCompositeColClause = "Select u from MongoPrimeUser u where u.key.userId = :userId";
    final String withClauseOnNoncomposite = "Select u from MongoPrimeUser u where u.tweetDate = ?1";
    // NOSQL Intelligence to teach that query is invalid because partition
    // key is not present?
    final String withSecondCompositeColClause = "Select u from MongoPrimeUser u where u.key.tweetId = :tweetId";
    final String withBothCompositeColClause = "Select u from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId";
    final String withAllCompositeColClause = "Select u from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId";
    final String withLastCompositeColGTClause = "Select u from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId >= :timeLineId";
    final String withSelectiveCompositeColClause = "Select u.key from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId";
    // query over 1 composite and 1 non-column
    // query with no clause.
    Query q = em.createQuery(noClause);
    List<MongoPrimeUser> results = q.getResultList();
    Assert.assertEquals(1, results.size());
    // Query with composite key clause.
    q = em.createQuery(withFirstCompositeColClause);
    q.setParameter("userId", "mevivs");
    results = q.getResultList();
    Assert.assertNotNull(results);
    Assert.assertEquals(1, results.size());
    // Query with composite key clause.
    q = em.createQuery(withFirstCompositeColClause);
    q.setParameter("userId", "kkmishra");
    results = q.getResultList();
    Assert.assertNotNull(results);
    Assert.assertEquals(0, results.size());
    // Query with composite key clause.
    q = em.createQuery(withClauseOnNoncomposite);
    q.setParameter(1, currentDate);
    results = q.getResultList();
    Assert.assertEquals(1, results.size());
    // Query with composite key clause.
    q = em.createQuery(withSecondCompositeColClause);
    q.setParameter("tweetId", 1);
    results = q.getResultList();
    Assert.assertNotNull(results);
    Assert.assertEquals(1, results.size());
    // Query with composite key clause.
    q = em.createQuery(withBothCompositeColClause);
    q.setParameter("userId", "mevivs");
    q.setParameter("tweetId", 1);
    results = q.getResultList();
    Assert.assertNotNull(results);
    Assert.assertEquals(1, results.size());
    // Query with composite key clause.
    q = em.createQuery(withAllCompositeColClause);
    q.setParameter("userId", "mevivs");
    q.setParameter("tweetId", 1);
    q.setParameter("timeLineId", timeLineId);
    results = q.getResultList();
    Assert.assertNotNull(results);
    Assert.assertEquals(1, results.size());
    // Query with composite key clause.
    q = em.createQuery(withLastCompositeColGTClause);
    q.setParameter("userId", "mevivs");
    q.setParameter("tweetId", 1);
    q.setParameter("timeLineId", timeLineId);
    results = q.getResultList();
    // TODO::
    Assert.assertEquals(1, results.size());
    // Query with composite key with selective clause.
    q = em.createQuery(withSelectiveCompositeColClause);
    q.setParameter("userId", "mevivs");
    q.setParameter("tweetId", 1);
    q.setParameter("timeLineId", timeLineId);
    results = q.getResultList();
    Assert.assertEquals(1, results.size());
    Assert.assertNull(results.get(0).getTweetBody());
    final String selectiveColumnTweetBodyWithAllCompositeColClause = "Select u.tweetBody from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId";
    // Query for selective column tweetBody with composite key clause.
    q = em.createQuery(selectiveColumnTweetBodyWithAllCompositeColClause);
    q.setParameter("userId", "mevivs");
    q.setParameter("tweetId", 1);
    q.setParameter("timeLineId", timeLineId);
    results = q.getResultList();
    Assert.assertEquals(1, results.size());
    Assert.assertEquals("my first tweet", results.get(0).getTweetBody());
    Assert.assertNull(results.get(0).getTweetDate());
    final String selectiveColumnTweetDateWithAllCompositeColClause = "Select u.tweetDate from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId";
    // Query for selective column tweetDate with composite key clause.
    q = em.createQuery(selectiveColumnTweetDateWithAllCompositeColClause);
    q.setParameter("userId", "mevivs");
    q.setParameter("tweetId", 1);
    q.setParameter("timeLineId", timeLineId);
    results = q.getResultList();
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(currentDate.getTime(), results.get(0).getTweetDate().getTime());
    Assert.assertNull(results.get(0).getTweetBody());
    final String withCompositeKeyClause = "Select u from MongoPrimeUser u where u.key = :key";
    // Query with composite key clause.
    q = em.createQuery(withCompositeKeyClause);
    q.setParameter("key", key);
    results = q.getResultList();
    Assert.assertNotNull(results);
    Assert.assertEquals(1, results.size());
    em.remove(user);
    // optional,just to clear persistence cache.
    em.clear();
}

97. MongoCompositeTypeTest#deleteNamed()

Project: Kundera
Source File: MongoCompositeTypeTest.java
View license
/**
     * delete by Named Query.
     */
private void deleteNamed() {
    UUID timeLineId = UUID.randomUUID();
    MongoCompoundKey key = new MongoCompoundKey("mevivs", 1, timeLineId);
    String deleteQuery = "Delete From MongoPrimeUser u where u.tweetBody= :tweetBody";
    EntityManager em = emf.createEntityManager();
    Query q = em.createQuery(deleteQuery);
    q.setParameter("tweetBody", "after merge");
    q.executeUpdate();
    em.close();
    em = emf.createEntityManager();
    MongoPrimeUser result = em.find(MongoPrimeUser.class, key);
    Assert.assertNull(result);
    em.close();
}

98. PersonGISDao#findNear()

Project: Kundera
Source File: PersonGISDao.java
View license
public List<Person> findNear(double x, double y, double maxDistance, SurfaceType surfaceType) {
    Point point = new Point(x, y);
    point.setSurfaceType(surfaceType);
    Query q = em.createQuery("Select p from Person p where p.currentLocation > :point AND p.currentLocation < :maxDistance");
    q.setParameter("point", point);
    q.setParameter("maxDistance", maxDistance);
    List<Person> persons = q.getResultList();
    return persons;
}

99. PersonGISDao#findWithinCircleAndName()

Project: Kundera
Source File: PersonGISDao.java
View license
/**
     * @param d
     * @param e
     * @param f
     * @param flat
     * @param string
     * @return
     */
public List<Person> findWithinCircleAndName(double x, double y, double r, SurfaceType surfaceType, String name) {
    Circle circle = new Circle(x, y, r);
    circle.setSurfaceType(surfaceType);
    Query q = em.createQuery("Select p from Person p where p.name = :name and p.currentLocation IN :circle");
    q.setParameter("name", name);
    q.setParameter("circle", circle);
    List<Person> persons = q.getResultList();
    return persons;
}

100. HBaseCompositeTypeTest#deleteNamed()

Project: Kundera
Source File: HBaseCompositeTypeTest.java
View license
/**
     * delete by Named Query.
     */
private void deleteNamed() {
    UUID timeLineId = UUID.randomUUID();
    HBaseCompoundKey key = new HBaseCompoundKey("mevivs", 1, timeLineId);
    String deleteQuery = "Delete From HBasePrimeUser u where u.tweetBody= :tweetBody";
    EntityManager em = emf.createEntityManager();
    Query q = em.createQuery(deleteQuery);
    q.setParameter("tweetBody", "after merge");
    q.executeUpdate();
    em.close();
    em = emf.createEntityManager();
    HBasePrimeUser result = em.find(HBasePrimeUser.class, key);
    Assert.assertNull(result);
    em.close();
}