Home > Articles > Programming > Java

Creating a Reusable CRUD RESTful Web Service to Automate Your Common Database Operations

  • Print
  • + Share This
Expert programmer Jesse Smith shows you how you can save time by creating a reusable CRUD RESTful web service. You'll learn how to make the Business Logic and Persistent layers of your application completely independent of your Presentation layer. By doing this, you can easily reuse the service for other applications.
Like this article? We recommend

Like this article? We recommend

This article continues my RESTful web service series by building on the most recent Informit article, “Expose Your JPA Entity Classes as RESTful Web Services.” In that article, you learned how to take an existing JPA Entity class (from my JPA Entity article) and quickly turned it into a RESTful web service.

To get started, let's use that JPA Entity class from the last article, but make it into our database Read operation. The Read operation basically issues a Select query to return results. If you don't have the workspace setup from the last article, please go back and do so now. It gives a step-by-step approach to setting up the environment for a JAX-RS web service using a database (Apache Derby).

Our database is a very simple setup for authenticating users, which can be used by many different applications at the same time. Think of the service as a repository for user authentication. You can add more columns to get or record more user attributes, but for the purposes of this article, I am going to keep it simple so you can build on this yourself. The first thing we need to do is create our Read operation for this service.

Database Read Operation

We already have a user class called User with a method called userList that returns the last user name in the users table to the screen. It is returning the results as plain text to the browser, but we'll change the output to JSON returned through the Response Header. Also, we need the userList method to accept a single parameter and return the results associated with this parameter. We'll pass the userId parameter through the URL string, though you can also pass it through the Request Body as well. The code below has our desired changes:

package crudOperations;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/users)
public class Users  {

    private static final String PERSISTENCE_UNIT_NAME = "User";
    private static EntityManagerFactory factory;
    private static String userName = null;
    
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{userId}{path:.*}")
    public Response userList(@PathParam("userId") int userId) {
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);		
        EntityManager em = factory.createEntityManager(); 
        Query q = em.createQuery("SELECT u FROM User u Where u.id = " + userId); 
        List<User> userList = q.getResultList();
         for (User user : userList) { 
             userName = user.Name; 
        } 
          String json = "{'user' : { 'name' : '" + userName + "' }}";  
          return Response.status(200).type("application/json").entity(json).build();  
    }
}

The output of the method is changed to the JSON format by designating that media type for the @Produces annotation. In order to pass the results back as JSON through the HTTP Response Header, a string called 'json' is created to hold the data. The Response object's entity method takes the json string and builds the output by adding it to the HTTP Response Header.

After running the service and using the URL http://localhost:8080/jaxrscrud/rest/users/1, you'll be prompted to download the response (because currently no client initiated the Request as we just used the browser only). Once you download and open the Response in Notepad, you'll see the User having an Id of '1' is returned in JSON format (per my example record):

{'user' : { 'name' : 'Tom Johnson' }}
  • + Share This
  • 🔖 Save To Your Account