Listing 4 shows a class data access object class, hence the name
TeamDao. We will get to the annotations on
this class shortly, but let me first explain the data access. The class has
a reference to the JPA class EntityManager.
This is a central class in JPA and provides access to the underlying
database. For your first method that retrieves all of the teams in the
league, use the EntityManager to create a
query. The query uses JPA's query language, which is very similar to SQL.
This query simply gets all of the Teams. For
the second method, you simply create a new Team
using the name of the team that is passed in, create a transaction, save
the new team, and commit the transaction using the
EntityManager. All of this code is vanilla JPA
code, as all of these classes and interfaces are part of the base API.
Now that you understand the JPA part of Listing 4, let's talk about the
JAX-RS aspects of it. The first thing you will notice is that you use the
@Path annotation to expose this to HTTP-based
clients. The /teams string specifies the
relative path to this class. The full URL path is going to be
/SoccerOrg/resources/teams. The
/SoccerOrg will specify the path to your web
application (of course, you can configure this to be something different,
or remove this completely). The /resources part
will be used to specify a JAX-RS end point. The
/teams corresponds to the @Path annotation and
specifies which of the JAX-RS classes to use.
Next, the first method, getAll, has a
@GET annotation on it. This specifies that this
method should be invoked if an HTTP GET request
is received. Next, the method has a @Produces
annotation. This declares the MIME type of the response. In this case, you
want to produce JSON, since that is the easiest thing to use with a
JavaScript-based client.
This is all you have to do to use JAX-RS to expose this class to web
clients. However, you might be asking yourself: If this method returns a
java.util.Collection of
Team objects, how will this be sent to web
clients? The @Produces annotation
declares that you want it to be sent as JSON, but how will the JAX-RS
serialize this into JSON? It turns out that all you need to enable this is
to add one more annotation to the Team class as
shown in Listing 5. |