Java Code Examples for javax.persistence.EntityManager#createNamedQuery()

The following examples show how to use javax.persistence.EntityManager#createNamedQuery() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void verifyJPANamedQuery(final EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    TypedQuery<Person> typedQuery = em.createNamedQuery(
            "get_person_by_name", Person.class);
    typedQuery.setParameter("name", "Quarkus");
    final Person singleResult = typedQuery.getSingleResult();

    if (!singleResult.getName().equals("Quarkus")) {
        throw new RuntimeException("Wrong result from named JPA query");
    }

    transaction.commit();
    em.close();
}
 
Example 2
Source File: CustomerProcessor.java    From cloud-espm-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Function Import implementation for getting customer by email address
 * 
 * @param emailAddress
 *            email address of the customer
 * @return customer entity.
 * @throws ODataException
 */
@SuppressWarnings("unchecked")
@EdmFunctionImport(name = "GetCustomerByEmailAddress", entitySet = "Customers", returnType = @ReturnType(type = Type.ENTITY, isCollection = true))
public List<Customer> getCustomerByEmailAddress(
		@EdmFunctionImportParameter(name = "EmailAddress") String emailAddress) throws ODataException {
	EntityManagerFactory emf = Utility.getEntityManagerFactory();
	EntityManager em = emf.createEntityManager();
	List<Customer> custList = null;
	try {

		Query query = em.createNamedQuery("Customer.getCustomerByEmailAddress");
		query.setParameter("emailAddress", emailAddress);

		try {

			custList = query.getResultList();
			return custList;

		} catch (NoResultException e) {
			throw new ODataApplicationException("No matching customer with Email Address:" + emailAddress,
					Locale.ENGLISH, HttpStatusCodes.BAD_REQUEST, e);
		}
	} finally {
		em.close();
	}
}
 
Example 3
Source File: TestNamedNativeQuery.java    From HibernateTips with MIT License 6 votes vote down vote up
@Test
public void namedNativeQuery() {
	log.info("... namedNativeQuery ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	Query q = em.createNamedQuery(Book.QUERY_SELECT_BY_ID);
	q.setParameter(1, 100);
	Book b = (Book) q.getSingleResult();
	Assert.assertTrue(b instanceof Book);
	Assert.assertEquals(new Long(100), ((Book)b).getId());
	
	em.getTransaction().commit();
	em.close();
}
 
Example 4
Source File: JPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void verifyJPANamedQuery(final EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    TypedQuery<Person> typedQuery = em.createNamedQuery(
            "get_person_by_name", Person.class);
    typedQuery.setParameter("name", "Quarkus");
    final Person singleResult = typedQuery.getSingleResult();

    if (!singleResult.getName().equals("Quarkus")) {
        throw new RuntimeException("Wrong result from named JPA query");
    }

    transaction.commit();
    em.close();
}
 
Example 5
Source File: DataLoader.java    From cloud-espm-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to parse the list of Customer Reviews (pre-populated
 * in the "com/sap/espm/model/data/CustomerReviews.xml" file) and return a
 * list of {@link CustomerReview}.
 * 
 * @param products
 *            - The List of {@link Product}
 * @return - The list of {@link CustomerReview}
 */
public List<CustomerReview> loadCustomerReviews(List<Product> products) {
	EntityManager em = emf.createEntityManager();
	TypedQuery<CustomerReview> queryReviews;
	List<CustomerReview> resReview = null;
	try {
		em.getTransaction().begin();
		queryReviews = em.createNamedQuery("CustomerReview.getAllCustomerReviews", CustomerReview.class);
		resReview = queryReviews.getResultList();
		if (resReview.size() > 5) {
			logger.info(resReview.size() + " Customer Reviews already available in the db");
		} else {
			new XMLParser().readCustomerReview(em, "com/sap/espm/model/data/CustomerReviews.xml", products);
			em.getTransaction().commit();
			queryReviews = em.createNamedQuery("CustomerReview.getAllCustomerReviews", CustomerReview.class);
			resReview = queryReviews.getResultList();
			logger.info(resReview.size() + " Products loaded into the db");
		}
	} catch (Exception e) {
		logger.error("Exception occured", e);
	} finally {
		em.close();
	}
	return resReview;
}
 
Example 6
Source File: ProductTest.java    From cloud-espm-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Test for multiple not existing products via Typed Queries
 */
@Test
public void testNotExistingProductsSearchTyped() {
	EntityManager em = emf.createEntityManager();
	List<Product> result = null;
	em.getTransaction().begin();
	try {
		// Search for mutiple Products.
		TypedQuery<Product> query = em.createNamedQuery("Product.getProductByCategory", Product.class);
		result = query.setParameter("category", "Trackpad").getResultList();
		assertEquals(
				"Search via typed query for not existing mutiple products: Product exists in database",
				0, result.size());
	} finally {
		em.close();
	}
}
 
Example 7
Source File: SalesOrderItemTest.java    From cloud-espm-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Test for multiple not existing Sales Order Items via Typed Queries
 */
@Test
public void testNotExistingSalesOrderItemsSearchTyped() {
	EntityManager em = emf.createEntityManager();
	List<SalesOrderItem> result = null;
	em.getTransaction().begin();
	try {
		// Search for mutiple SO Item.
		TypedQuery<SalesOrderItem> query = em.createNamedQuery("SalesOrderItem.getSOIByCurrencyCode",
				SalesOrderItem.class);
		result = query.setParameter("currencyCode", "INV").getResultList();
		assertEquals(
				"Search via typed query for not existing mutiple Sales Order Items: Sales Order Items exists in database",
				0, result.size());
	} finally {
		em.close();
	}
}
 
Example 8
Source File: CommonDAOSpringImpl.java    From EasyEE with MIT License 6 votes vote down vote up
/**
 * CommonDAO 内部方法,NamedQuery
 * 
 * @param entityManager
 *            entityManager
 * @param name
 *            name
 * @param cacheable
 *            cacheable
 * @param cacheRegion
 *            cacheRegion
 * @param values
 *            values
 * @return Query对象
 */
private Query createNamedQuery(EntityManager entityManager, String name, boolean cacheable, String cacheRegion,
		Map<String, Object> values) {
	Query query = entityManager.createNamedQuery(name.trim());
	if (cacheable) {
		query.setHint(QueryHints.HINT_CACHEABLE, "true");
		if (cacheRegion != null && (!cacheRegion.equals(""))) {
			query.setHint(QueryHints.HINT_CACHE_REGION, cacheRegion);
		}
	}
	if (values != null && values.size() > 0) {
		for (Entry<String, Object> e : values.entrySet()) {
			query.setParameter(e.getKey(), e.getValue());
		}
	}
	return query;
}
 
Example 9
Source File: StockTest.java    From cloud-espm-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Test for multiple existing stocks generated via algorithm via Typed
 * Queries
 */
@Test
public void testExistingProductsSearchTyped() {
	EntityManager em = emf.createEntityManager();
	try {
		DataLoader dl = new DataLoader(emf);
		List<Product> products = dl.loadProducts(null);
		dl.loadStock(products);
		// Search for mutiple Stocks.
		TypedQuery<Stock> query = em.createNamedQuery("Stock.getAllStocks", Stock.class);
		List<Stock> result = query.getResultList();

		assertTrue(
				"Search for mutiple existing stocks: Multiple stocks not added",
				result.size() > 2);
	} finally {
		em.close();
	}
}
 
Example 10
Source File: CommonDAOSpringImpl.java    From EasyEE with MIT License 6 votes vote down vote up
/**
 * CommonDAO 内部方法,NamedQuery
 * 
 * @param entityManager
 *            entityManager
 * @param name
 *            name
 * @param cacheable
 *            cacheable
 * @param cacheRegion
 *            cacheRegion
 * @param values
 *            values
 * @return Query对象
 */
private Query createNamedQuery(EntityManager entityManager, String name, boolean cacheable, String cacheRegion,
		Map<String, Object> values) {
	Query query = entityManager.createNamedQuery(name.trim());
	if (cacheable) {
		query.setHint(QueryHints.HINT_CACHEABLE, "true");
		if (cacheRegion != null && (!cacheRegion.equals(""))) {
			query.setHint(QueryHints.HINT_CACHE_REGION, cacheRegion);
		}
	}
	if (values != null && values.size() > 0) {
		for (Entry<String, Object> e : values.entrySet()) {
			query.setParameter(e.getKey(), e.getValue());
		}
	}
	return query;
}
 
Example 11
Source File: DatabaseClientService.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
@Override
public void removePendingTokensForUser(IUser user) {
	EntityManager entityManager = emf.createEntityManager();
	EntityTransaction tx = entityManager.getTransaction();
	try {
		tx.begin();
		TypedQuery<PendingClientToken> query = entityManager.createNamedQuery("findPendingByUser", PendingClientToken.class);
		query.setParameter("username", user.getName());
		for (PendingClientToken token : query.getResultList())
		{
			entityManager.remove(token);
		}
		tx.commit();
	} catch (PersistenceException e) {
		LOGGER.error(PERSISTENCE_ERROR, e);
		tx.rollback();
		throw e;			
	} finally {
		entityManager.close();
	}		
}
 
Example 12
Source File: SupplierTest.java    From cloud-espm-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Test for multiple existing Suppliers added from Business_Partners.xml via
 * Typed Queries
 */
@Test
public void testExistingSuppliersSearchTyped() {
	EntityManager em = emf.createEntityManager();
	try {
		DataLoader dl = new DataLoader(emf);
		dl.loadSuppliers();
		// Search for mutiple Suppliers.
		TypedQuery<Supplier> query = em.createNamedQuery("Supplier.getAllSuppliers", Supplier.class);
		List<Supplier> result = query.getResultList();
		assertTrue(
				"Search for mutiple existing Suppliers: Multiple Suppliers not added",
				result.size() > 2);
	} catch (Exception e) {
		fail("Exception " + e + " occured");
	} finally {
		em.close();
	}
}
 
Example 13
Source File: JPAPersistenceManagerService.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
@Override
public List<Long> jobOperatorGetJobInstanceIds(final String jobName, final int start, final int count) {
    final EntityManager em = emProvider.newEntityManager();
    try {
        final TypedQuery<JobInstanceEntity> query;
        query = em.createNamedQuery(JobInstanceEntity.Queries.FIND_BY_NAME, JobInstanceEntity.class);
        query.setParameter("name", jobName);

        final List<JobInstanceEntity> resultList = query
            .setFirstResult(start)
            .setMaxResults(count)
            .getResultList();

        if (resultList == null) {
            return Collections.emptyList();
        }

        final List<Long> result = new ArrayList<Long>(resultList.size());
        for (final JobInstanceEntity entity : resultList) {
            result.add(entity.getJobInstanceId());
        }
        return result;
    } finally {
        emProvider.release(em);
    }
}
 
Example 14
Source File: ProductCategoryTest.java    From cloud-espm-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Test if a single product category can be added and checks if it exists
 * via TypedQuery-SetParamter
 */
@Test
public void testExistingProductcategorySearchTyped() {
	ProductCategory prodCatResult = null;
	String prodCategory = "Phablets";
	EntityManager em = emf.createEntityManager();

	TestFactory tf = new TestFactory();
	try {
		// Add Product
		assertTrue("Product category not created",
				tf.createProductCategory(em, prodCategory));
		em.getTransaction().begin();

		// Search for Product category
		TypedQuery<ProductCategory> query = em.createNamedQuery("ProductCategory.getProductCategoryByCategory",
				ProductCategory.class);
		prodCatResult = query.setParameter("category", prodCategory)
				.getSingleResult();

		assertEquals(
				"Search via typed query for existing product category : Added Product category not persisted in the database",
				prodCategory, prodCatResult.getCategory());
	} catch (NoResultException ne) {
		assertNotNull(
				"Search via typed query for existing product category: Added Product category  not persisted in the database",
				prodCatResult);
	} finally {
		em.close();
	}
}
 
Example 15
Source File: JpaItemReader.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
private Collection<?> nextPage() {
    final EntityManager em = emProvider.getValue().newEntityManager();
    if (transaction) {
        em.getTransaction().begin();
    }
    final Query jpaQuery;
    try {
        if (namedQuery != null) {
             jpaQuery = em.createNamedQuery(namedQuery);
        } else {
            jpaQuery = em.createQuery(query);
        }
        jpaQuery.setFirstResult(firstResult).setMaxResults(page);
        if (paramProvider != null) {
            paramProvider.getValue().setParameters(jpaQuery);
        }
        final List<?> resultList = jpaQuery.getResultList();
        if (detach) {
            for (final Object o : resultList) {
                em.detach(o);
            }
        }
        return resultList;
    } finally {
        if (transaction) {
            em.getTransaction().commit();
        }
        emProvider.getValue().release(em);
    }
}
 
Example 16
Source File: MCRIView2Commands.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@MCRCommand(syntax = "fix dead tile jobs", help = "Deletes entries for files which dont exist anymore!")
public static void fixDeadEntries() {
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    TypedQuery<MCRTileJob> allTileJobQuery = em.createNamedQuery("MCRTileJob.all", MCRTileJob.class);
    List<MCRTileJob> tiles = allTileJobQuery.getResultList();
    tiles.stream()
        .filter(tj -> {
            MCRPath path = MCRPath.getPath(tj.getDerivate(), tj.getPath());
            return !Files.exists(path);
        })
        .peek(tj -> LOGGER.info("Delete TileJob {}:{}", tj.getDerivate(), tj.getPath()))
        .forEach(em::remove);
}
 
Example 17
Source File: UserDAO.java    From cloud-sfsf-benefits-ext with Apache License 2.0 5 votes vote down vote up
public User getByUserId(String userId) {
	final EntityManager em = emProvider.get();
	try {
		final TypedQuery<User> query = em.createNamedQuery(DBQueries.GET_USER_BY_USER_ID, User.class);
		query.setParameter("userId", userId); //$NON-NLS-1$
		User user = query.getSingleResult();
		return user;
	} catch (NoResultException x) {
		logger.warn("Could not retrieve entity for userId {} from table {}. Maybe the user doesn't exist yet.", userId, "User"); //$NON-NLS-1$ //$NON-NLS-2$
	} catch (NonUniqueResultException ex) {
		throw new IllegalStateException(String.format("More than one entity for userId %s from table User.", userId), ex); //$NON-NLS-1$
	}

	return null;
}
 
Example 18
Source File: MCRMetadataHistoryManager.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static Map<MCRObjectID, Instant> getDeletedItems(Instant from, Optional<Instant> until) {
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    TypedQuery<MCRMetaHistoryItem> query = em.createNamedQuery("MCRMetaHistory.getLastEventByID",
        MCRMetaHistoryItem.class);
    query.setParameter("from", from);
    query.setParameter("until", until.orElseGet(Instant::now));
    query.setParameter("eventType", MCRMetadataHistoryEventType.Delete);
    return query.getResultList()
        .stream()
        .collect(Collectors.toMap(MCRMetaHistoryItem::getId, MCRMetaHistoryItem::getTime));
}
 
Example 19
Source File: TradeJPADirect.java    From jboss-daytrader with Apache License 2.0 4 votes vote down vote up
public MarketSummaryDataBean getMarketSummary() {
    MarketSummaryDataBean marketSummaryData;

    /*
     * Creating entiManager
     */
    EntityManager entityManager = emf.createEntityManager();

    try {
        if (Log.doTrace())
            Log.trace("TradeJPADirect:getMarketSummary -- getting market summary");

        // Find Trade Stock Index Quotes (Top 100 quotes)
        // ordered by their change in value
        Collection<QuoteDataBean> quotes;

        Query query = entityManager
                      .createNamedQuery("quoteejb.quotesByChange");
        quotes = query.getResultList();

        QuoteDataBean[] quoteArray = (QuoteDataBean[]) quotes.toArray(new QuoteDataBean[quotes.size()]);
        ArrayList<QuoteDataBean> topGainers = new ArrayList<QuoteDataBean>(
                                                                          5);
        ArrayList<QuoteDataBean> topLosers = new ArrayList<QuoteDataBean>(5);
        BigDecimal TSIA = FinancialUtils.ZERO;
        BigDecimal openTSIA = FinancialUtils.ZERO;
        double totalVolume = 0.0;

        if (quoteArray.length > 5) {
            for (int i = 0; i < 5; i++)
                topGainers.add(quoteArray[i]);
            for (int i = quoteArray.length - 1; i >= quoteArray.length - 5; i--)
                topLosers.add(quoteArray[i]);

            for (QuoteDataBean quote : quoteArray) {
                BigDecimal price = quote.getPrice();
                BigDecimal open = quote.getOpen();
                double volume = quote.getVolume();
                TSIA = TSIA.add(price);
                openTSIA = openTSIA.add(open);
                totalVolume += volume;
            }
            TSIA = TSIA.divide(new BigDecimal(quoteArray.length),
                               FinancialUtils.ROUND);
            openTSIA = openTSIA.divide(new BigDecimal(quoteArray.length),
                                       FinancialUtils.ROUND);
        }

        marketSummaryData = new MarketSummaryDataBean(TSIA, openTSIA,
                                                      totalVolume, topGainers, topLosers);
    }
    catch (Exception e) {
        Log.error("TradeJPADirect:getMarketSummary", e);
        throw new RuntimeException("TradeJPADirect:getMarketSummary -- error ", e);
    } finally {
        entityManager.close();
    }

    return marketSummaryData;
}
 
Example 20
Source File: SalesOrderProcessor.java    From cloud-espm-v2 with Apache License 2.0 4 votes vote down vote up
/**
 * Function Import implementation for getting all the Sales Order Items
 * under a Sales Order Header
 * 
 * @param SalesOrderId
 *            Sales Order Id of a Sales Order
 * @return SalesOrderItem entity.
 * @throws ODataException
 */
@SuppressWarnings("unchecked")
@EdmFunctionImport(name = "GetSalesOrderItemsById", entitySet = "SalesOrderItems", returnType = @ReturnType(type = Type.ENTITY, isCollection = true))
public List<SalesOrderItem> getSalesOrderById(
		@EdmFunctionImportParameter(name = "SalesOrderId") String salesOrderId) throws ODataException {
	EntityManagerFactory emf = Utility.getEntityManagerFactory();
	EntityManager em = emf.createEntityManager();
	List<SalesOrderItem> soiList = null;
	try {

		Query query = em.createNamedQuery("SalesOrderItem.getSOIBySalesOrderItemId");
		query.setParameter("id", salesOrderId);

		try {

			soiList = query.getResultList();
			if (soiList != null && soiList.size() >= 1) {

				for (SalesOrderItem salesOrderItem : soiList) {
					query = em.createNamedQuery("Product.getProductByProductId");
					query.setParameter("productId", salesOrderItem.getProductId());
					Product product = (Product) query.getSingleResult();
					salesOrderItem.setProduct(product);

				}
				// if the sales order are fetched successfully, generate the
				// pdf report data.
				try {
					if (CMISSessionHelper.getInstance().getSession() != null) {
						InvoiceBuilder builder = new InvoiceBuilder();
						String reportPath = builder.generateInvoice(soiList);
						updateSalesOrderHeader(reportPath, soiList, em);
					}
				} catch (CMISConnectionException cmisConnectionException) {
					// There was an exception while generating the report.
					LOGGER.error(cmisConnectionException.getMessage());
				}
				
				

			}

		} catch (NoResultException e) {
			throw new ODataApplicationException("No matching Sales Order with Sales Order Id:" + salesOrderId,
					Locale.ENGLISH, HttpStatusCodes.BAD_REQUEST, e);
		} catch (ReportGenerationException reportGenerationException) {
			//LOGGER.error("Exception while generating the report : " + reportGenerationException.getMessage());
			reportGenerationException.printStackTrace();
			throw new ODataApplicationException("PDF Report Generation Error for :" + salesOrderId,
					Locale.ENGLISH, HttpStatusCodes.INTERNAL_SERVER_ERROR, reportGenerationException);
		}

		return soiList;
	} finally {
		em.close();
	}
}