Home > Articles > Programming > Java

Expose Your JPA Entity Classes as RESTful Web Services

  • Print
  • + Share This
Expert programmer Jesse Smith shows you how you can expose parts of your Java application as RESTful Web services. You’ll learn to leverage what you already have or with the new classes you create by making their functionality reusable through a JAX-RS Web service.
Like this article? We recommend

If you're unfamiliar with what RESTful web services are, please visit my previous article on using RESTful web services for an introduction. The purpose of this article is to build on what was learned from that article.

RESTful Web services have been around for awhile now, and are gaining more popularity than your traditional SOAP-based web services. The biggest reason is because a RESTful web service allows you to browse an application's resources much like the web. Because a RESTful web service is HTTP-centric, each service operation maps to an HTTP method. Mapping to HTTP methods have been around and used since the early days of the Internet, making RESTful web services an ideal choice for automating your basic database Create, Read, Update and Delete (CRUD) operations.

However, you still have to expose your Entity classes in a way that allows these classes to function as they always have, while also giving them a URI and having them function as a web service.

In this article, you’ll learn how to do this. In a later article, I’ll show how you can do your basic database (CRUD) operations for each Entity. For now though, we’ll expose a JPA Entity class and have it return the names of users in a database.

Annotations

JAX-RS, like many of the modern Java specifications, uses annotations to create different behaviors for your service class. A quick review of what the most common JAX-RS annotations are is specified below:

  • @PATH(your_path): Sets the path to base URL + /your_path. The base URL is based on your application name, the servlet, and the URL pattern from the web.xml configuration file.
  • @POST: Indicates that the following method will answer to an HTTP POST request.
  • @GET: Indicates that the following method will answer to an HTTP GET request.
  • @PUT: Indicates that the following method will answer to an HTTP PUT request.
  • @DELETE: Indicates that the following method will answer to an HTTP DELETE request.
  • @Produces( MediaType.TEXT_PLAIN [, more-types ] ): Defines which MIME type is delivered by a method annotated with @GET. In the example text, ("text/plain" ) is produced. Other examples would be application/xml or application/json.
  • @Consumes( type [, more-types ] ): Defines which MIME type is consumed by this method.
  • @PathParam: Used to inject values from the URL into a method parameter.
  • + Share This
  • 🔖 Save To Your Account