background image

Building the order Application

<< Setting Entity Relationships | Creating the Database Tables >>
<< Setting Entity Relationships | Creating the Database Tables >>

Building the order Application

@NamedQuery(
name=
"findAllOrders",
query=
"SELECT o FROM Order o"
)
The EntityManager.createNamedQuery method is used to run the query. Because the query
returns a List of all the orders, the Query.getResultList method is used.
List orders = em.createNamedQuery(
"findAllOrders")
.getResultList();
The RequestBean.getTotalPricePerVendor business method returns the total price of all the
parts for a particular vendor. It uses a named parameter, id, defined in the named query
findTotalVendorPartPricePerVendor
defined in VendorPart.
@NamedQuery(
name=
"findTotalVendorPartPricePerVendor",
query=
"SELECT SUM(vp.price) " +
"FROM VendorPart vp " +
"WHERE vp.vendor.vendorId = :id"
)
When running the query, the Query.setParameter method is used to set the named parameter
id
to the value of vendorId, the parameter to RequestBean.getTotalPricePerVendor.
return (Double) em.createNamedQuery(
"findTotalVendorPartPricePerVendor")
.setParameter(
"id", vendorId)
.getSingleResult();
The Query.getSingleResult method is used for this query because the query returns a single
value.
Removing Entities
The RequestBean.removeOrder business method deletes a given order from the database. It
uses the EntityManager.remove method to delete the entity from the database.
Order order = em.find(Order.class, orderId);
em.remove(order);
Building and Running the order Application
This section describes how to build, package, deploy, and run the order application. To do this,
you will create the database tables in the Java DB server, then build, deploy, and run the
example.
The order Application
Chapter 26 · Persistence in the EJB Tier
721