Hey there!
I’m excited to show you how to create a Jax-RS CRUD application that works with MongoDB. If you’re not familiar with Jax-RS, it’s a Java API for RESTful web services. It makes it easy to build web services that can create, read, update, and delete resources.
I personally love using Jax-RS because it’s simple to use and easy to set up. Plus, with the latest MongoDB ORM Java driver API, it’s super easy to connect our Jax-RS application to a MongoDB database and perform CRUD operations.
Before we get started, let’s make sure you have all the necessary tools. You’ll need the following:
Java 8 or higher
Maven 3.6 or higher
MongoDB 4.7 or higher
The latest MongoDB ORM Java driver API (we’ll be using version 4.7 in this tutorial)
Now, let’s set up our Maven file. Here’s what your pom.xml file should look like:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>jaxrs-mongodb-crud</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!– Jax-RS dependencies –>
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>10.0</version>
<scope>provided</scope>
</dependency>
<!– MongoDB ORM Java driver dependencies –>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.7.0</version>
</dependency>
</dependencies>
</project>
Great! Now that we have our Maven file set up, let’s create our Java files.
First, let’s create a POJO (Plain Old Java Object) for our resource. This will be a simple class that represents a single resource in our database. For example, if we’re creating a CRUD application for a blog, our resource might be a Post class with fields like title, content, and author.
Here’s an example Post class:
import org.bson.codecs.pojo.annotations.BsonId; public class Post { @BsonId private String id; private String title; private String content; private String author; // Getters and setters go here }
Next, let’s create a class for our CRUD operations. This class will use the MongoDB ORM Java driver to connect to our database and perform the necessary CRUD operations.
import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import org.bson.types.ObjectId; public class PostService { private MongoClient mongoClient; private MongoDatabase database; private MongoCollection < Post > collection; public PostService() { // Connect to MongoDB using the MongoClient class mongoClient = MongoClients.create(); // Select the database and collection we want to use database = mongoClient.getDatabase("myDatabase"); collection = database.getCollection("posts", Post.class); } public Post create(Post post) { // Insert the new post into the collection and return it collection.insertOne(post); return post; } public Post read(String id) { // Find the post with the specified ID and return it return collection.find(Filters.eq("_id", new ObjectId(id))).first(); } public Post update(Post post) { // Replace the existing post with the updated one and return it collection.replaceOne(Filters.eq("_id", new ObjectId(post.getId())), post); return post; } public void delete(String id) { // Delete the post with the specified ID collection.deleteOne(Filters.eq("_id", new ObjectId(id))); } }
Now that we have our POJO and service class set up, let’s create a Jax-RS resource class to handle our HTTP requests. This class will use the `PostService` class to perform the actual CRUD operations and return the appropriate response to the client.
Here’s an example of a `PostResource` class:
import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; @Path("/posts") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class PostResource { private PostService service = new PostService(); @POST public Response create(Post post) { Post createdPost = service.create(post); return Response.status(Response.Status.CREATED).entity(createdPost).build(); } @GET @Path("{id}") public Response read(@PathParam("id") String id) { Post post = service.read(id); if (post == null) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(post).build(); } @PUT @Path("{id}") public Response update(@PathParam("id") String id, Post post) { Post updatedPost = service.update(post); if (updatedPost == null) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(updatedPost).build(); } @DELETE @Path("{id}") public Response delete(@PathParam("id") String id) { service.delete(id); return Response.ok().build(); } }
That’s it! You now have a fully functional Jax-RS CRUD application that works with MongoDB. To test it out, you can use a tool like Postman to send HTTP requests to your application and see the results.
I hope this tutorial has been helpful and showed you how easy it is to create a Jax-RS CRUD application with MongoDB. If you have any questions or need any additional help, don’t hesitate to ask. Happy coding!