- Database Read Operation
- Database Create, Update, and Delete Operations
Database Create Operation
For the Create/Post operation, there are multiple ways to do this, depending on what your Create method will consume as input (i.e., JSON, XML, etc.). Each input type is handled a little differently. Because we're already working with JSON, the createUser method of our User class will be expecting JSON for input. To create this method for posting users, start with the annotations below:
@POST @Path(/create) @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
The above annotations tell the method to expect and return JSON. The method will handle the user request using the HTTP Post method. When the URL contains the word 'create' (from the @PATH annotation), it will use this method. The rest is easy, as JAX-RS does most of the work. Our class only needs to look like this:
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/create") public Response createUser(User user) { factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); EntityManager em = factory.createEntityManager(); em.persist(user); String json = "{'OK'}"; return Response.status(200).type("application/json").entity(json).build(); }
Of course, we could add an Exception if it does not post correctly, but to keep it more simplified, just passing back an OK will tell our client there was no problems posting the new record. By passing in the User type to the method, we tell JAX-RS that when parsing the JSON input, to look for a type called User. In the User type, there will be field names that map to the database field names. JAX-RS knows enough to map these values to your new User object (by using JAXB to convert the JSON input to a User type). All that is left to do then is persist the new User.
You client only needs to pass the JSON string for the new User to the Request Body and posting to the service URL.
Database Update Operation
The Update operation is very similar to our listUser method. We can simply copy that method and rename it to 'updateUser' and add a few small changes:
@PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/update/{userId}{path:.*}") public Response updateUser(User user, @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); User userToUpdate = em.getReference(User.class, userId); userToUpdate = user; em.persist(userToUpdate); String json = "{'OK'}"; return Response.status(200).type("application/json").entity(json).build(); }
For this method, we add a new sub-path to update an existing User. The id of the User to update is padded through the URL. The method pulls the userId and finds that User object using the JPA Entity Manager. The user type that is being passed through the method declaration is converted from JSON to a Java object using JAXB. The only thing left to do is update the existing User object with the new User data passed in as a JSON input string.
Database Delete Operation
Even easier yet, to do the Delete operation, all we have to do is copy the Update method and make a few small changes:
@DELETE @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/delete/{userId}{path:.*}") public Response deleteUser(User user, @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); User userToDelete = em.getReference(User.class, userId); userToDelete = user; em.remove(userToDelete); String json = "{'OK'}"; return Response.status(200).type("application/json").entity(json).build(); }
Conclusion
This article should put you on the fast track for using JAX-RS and JPA together in the form of doing your basic database CRUD operations. The idea is to expand on these methods to suit your project, and encourage you to try some different input and output formats when doing these operations.
In later articles, I'd like to show you how Spring and Hibernate work together and with using JAX-RS services as well.