Jump to: navigation, search

EclipseLink/Examples/REST/GettingStarted/RestService

Overview

Java API for RESTful Web Services (JAX-RS) is the Java EE standard for creating RESTful Web Services. In this post we will create a RESTful service from an EJB session bean using JAX-RS.

Customer Service

We will use the @PersistenceContent annotation to inject an EntityManager onto our EJB session bean. We will use this EntityManager to perform all of our persistence operations. Back in part 2 we configured our persistence unit to use the Java Transaction API (JTA), so we will not need to do any of our own transaction handling.

You can see below how little JPA code is required to implement our RESTful service. Of course to make this production quality service we will need to include response objects and exception handling. In future posts I'll cover these topics in detail. For the purpose of this example the following is all the code you need to run your service.

package org.example;
 
import java.util.List;
 
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
 
@Stateless
@LocalBean
@Path("/customers")
public class CustomerService {
 
    @PersistenceContext(unitName="CustomerService", 
                        type=PersistenceContextType.TRANSACTION)
    EntityManager entityManager;
 
    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public void create(Customer customer) {
        entityManager.persist(customer);
    }
 
    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("{id}")
    public Customer read(@PathParam("id") long id) {
        return entityManager.find(Customer.class, id);
    }
 
    @PUT
    @Consumes(MediaType.APPLICATION_XML)
    public void update(Customer customer) {
        entityManager.merge(customer);
    }
 
    @DELETE
    @Path("{id}")
    public void delete(@PathParam("id") long id) {
        Customer customer = read(id);
        if(null != customer) {
            entityManager.remove(customer);
        }
    }
 
    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("findCustomersByCity/{city}")
    public List<Customer> findCustomersByCity(@PathParam("city") String city) {
        Query query = entityManager.createNamedQuery("findCustomersByCity");
        query.setParameter("city", city);
        return query.getResultList();
    }
 
}

WEB-INF/web.xml

In the WEB-INF/web.xml file we need to configure three things:

  1. Start the Jersey service for our application. We will use the Jersey implmenation of JAX-RS, it is included in the version of GlassFish we are using for this example.
  2. You interact with JAX-RS through URIs. We need to tell Jersey which URLs (a URL is a type of URI) relate our service. In our web context URLs starting with "rest" correspond to our RESTful service.
  3. We need to make our JPA persistence context we created in part 3 available for use by our EJB session bean.
<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    <persistence-context-ref>
        <persistence-context-ref-name>persistence/em</persistence-context-ref-name>
        <persistence-unit-name>CustomerService</persistence-unit-name>
    </persistence-context-ref>
</web-app>

Packaging/Deployment

We will package up everying in a WAR file. The JAR file containing the contents we created in part 2 and part 3 should be inluded in the war in the directory WEB-INF/lib.

CustomerService.war

  • WEB-INF
    • lib
      • CustomerService.jar
        • org
          • example
            • Customer.class
            • Address.class
            • PhoneNumber.class
            • jaxb.properties
  • META-INF
    • MANIFEST.MF
    • persistence.xml
  • classes
    • org
      • example
        • CustomerService.class
    • web.xml
  • META-INF
    • MANIFEST.MF

Next Steps

In the next post we'll look at creating a client for our RESTful service.