DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Efficient Data Management With Offset and Cursor-Based Pagination in Modern Applications
  • Spring Boot Application With Spring REST and Spring Data MongoDB
  • CRUDing NoSQL Data With Quarkus, Part One: MongoDB

Trending

  • The Role of Retrieval Augmented Generation (RAG) in Development of AI-Infused Enterprise Applications
  • Grafana Loki Fundamentals and Architecture
  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • How to Build Local LLM RAG Apps With Ollama, DeepSeek-R1, and SingleStore
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Building a MongoDB-Powered RESTful Application With Quarkus and Eclipse JNoSQL

Building a MongoDB-Powered RESTful Application With Quarkus and Eclipse JNoSQL

Build a MongoDB-powered RESTful app with Quarkus and Eclipse JNoSQL: generate, configure, create entities, implement services, and expose API.

By 
Otavio Santana user avatar
Otavio Santana
DZone Core CORE ·
Jul. 10, 23 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
7.6K Views

Join the DZone community and get the full member experience.

Join For Free

In the rapidly evolving world of modern application development, the adoption of NoSQL databases has gained significant traction due to their flexible data models and scalability advantages. However, integrating NoSQL databases seamlessly into an application can sometimes be complex, requiring specialized knowledge and intricate configurations. Enter Eclipse JNoSQL and Quarkus, two powerful technologies that, when combined, simplify the integration process and enable developers to leverage the capabilities of NoSQL databases effortlessly.

Eclipse JNoSQL is an open-source framework that provides a standardized API and tools for working with NoSQL databases. It offers a unified programming model that abstracts the complexities of various NoSQL databases, allowing developers to write code agnostic to the underlying database technology. JNoSQL supports a wide range of NoSQL databases, including MongoDB, Cassandra, Couchbase, and more, making it an excellent choice for building flexible and scalable applications.

On the other hand, Quarkus has emerged as a leading framework for developing Java applications with unprecedented speed and low memory consumption. Built with container-first principles, Quarkus optimizes application performance for cloud-native environments and provides a developer-friendly experience through live coding, seamless hot-reloading, and efficient deployment options. With its impressive ecosystem of extensions, Quarkus enables developers to integrate with various technologies and libraries effortlessly.

By combining the power of Eclipse JNoSQL and the agility of Quarkus, developers can unlock a new level of simplicity and productivity in building applications that interact with NoSQL databases. The seamless integration between the two technologies allows developers to focus on their core business logic without being burdened by the intricacies of database interactions.

This article will explore a practical example demonstrating creating a RESTful API application using MongoDB as the underlying NoSQL database. We will dive into live coding and witness firsthand how Eclipse JNoSQL and Quarkus work harmoniously to provide a streamlined development experience. Throughout the example, we'll highlight the ease with which developers can interact with NoSQL databases, thanks to the combined efforts of Eclipse JNoSQL and Quarkus.

This article aims to showcase the seamless collaboration between Eclipse JNoSQL and Quarkus. By the end, readers will understand how these technologies combine to create an environment that enables rapid development and effortless integration with NoSQL databases. So, let's embark on this journey and witness firsthand the power of Eclipse JNoSQL and Quarkus in action.

Quarkus and Eclipse JNoSQL in Action

Let's start our application sample with Quarkus and Eclipse JNoSQL technologies. And the best part? We can kickstart the development process effortlessly using the Quarkus starting code.

Step 1: Generating a Quarkus Application 

To simplify and expedite the application setup process, we'll leverage the Quarkus starting code. Follow these steps to generate your Quarkus application with the required dependencies:

  1. Visit the Quarkus starting code website.
  2. Choose your preferred build tool, such as Maven or Gradle.
  3. Select the Quarkus version that suits your needs.
  4. Click on Add Extension and search for the quarkus-jnosql-document-mongodb and quarkus-resteasy-jsonb extensions. These extensions enable seamless integration with MongoDB and RESTful API development, respectively.
  5. Once you select the necessary extensions, click Generate your application to obtain a downloadable project.

Quarkus generation with Eclipse JNoSQL

Quarkus code generation

Step 2: Java Faker

To add some randomness and variety to our Fish entities, we can utilize the Java Faker library. This library allows us to generate real and random data, including fish names. Follow the steps below to integrate Java Faker into our project:

Open the pom.xml file located in the root directory of your project.

Add the following dependency within the <dependencies> section:

XML
 
<dependency>
    <groupId>com.github.javafaker</groupId>
    <artifactId>javafaker</artifactId>
    <version>1.0.2</version>
</dependency>


Save the pom.xml file.

Step 3: Create Fish Entity Class

Now, let's create the Fish entity class with three fields: id, name, and color. We will utilize the Entity, Id, and Column annotations to define this class as an entity, specify the identifier, and mark the persistable fields. Create a new Java class called Fish in the desired package and implement the following code:

Java
 
@Entity
public class Fish {

    @Id
    public String id;

    @Column
    public String name;

    @Column
    public String color;

 }


The Id annotation marks the id field as the identifier for the Fish entity, while the Column annotation marks the name and color fields as persistable columns.

Step 4: Create FishService Class

We'll create the FishService class to handle the NoSQL database API using Eclipse JNoSQL. The FishService will be responsible for performing CRUD operations on the Fish entities. We'll utilize the Template interface provided by Eclipse JNoSQL. Create a new Java class called FishService in the desired package and implement the following code:

Java
 
@ApplicationScoped
public class FishService {

    @Inject
    private DocumentTemplate template;

    private final Faker faker = new Faker();


    public List<Fish> findAll() {
        return template.select(Fish.class).result();
    }

    public Fish insert(Fish fish) {
        fish.id = UUID.randomUUID().toString();
        return this.template.insert(fish);
    }

    public void delete(String id) {
        this.template.delete(Fish.class, id);
    }

    public Optional<Fish> findById(String id){
        return this.template.find(Fish.class, id);
    }

    public Fish random() {
        Fish fish = new Fish();
        Animal animal = faker.animal();
        fish.id = UUID.randomUUID().toString();
        fish.name = animal.name();
        fish.color = faker.color().name();
        return this.template.insert(fish);
    }

    public Optional<Fish> update(String id, Fish fish) {
        Optional<Fish> optional = this.template.find(Fish.class, new ObjectId(id));
        return optional.map(f -> {
            f.name = fish.name;
            f.color = fish.color;
            return this.template.update(f);
        });

    }

}


In this example, we've created a FishService class annotated with @ApplicationScoped to indicate that it is a managed bean in the application context. We've injected the DocumentTemplate provided by Eclipse JNoSQL using @Inject annotation.

The FishService class provides various methods to interact with the Fish entities. We have implemented methods for finding all Fish entities, inserting a new Fish entity, deleting a Fish entity by ID, finding a Fish entity by ID, generating a random Fish entity using Java Faker, and updating a Fish entity.

The random() method demonstrates the usage of Java Faker to generate random fish names and colors. We assign a new UUID to the Fish entity's ID and use the DocumentTemplate to insert it into the database.

With the FishService in place, we now have a service layer that encapsulates the database operations for Fish entities. In the next step, we will create FishResource to expose the service methods as RESTful API endpoints.

Step 5: Create FishResource Class

In this step, we'll create the FishResource class representing the integration between our Fish entity and the users needing the information. The FishResource class will expose the service methods as RESTful API endpoints. Create a new Java class called FishResource in the desired package and implement the following code:

Java
 
@Path("/fishes")
@ApplicationScoped
public class FishResource {

    @Inject
    private FishService service;

    @GET
    @Path("{id}")
    public Fish findId(@PathParam("id") String id) {
        return service.findById(id)
                .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND));
    }

    @GET
    @Path("random")
    public Fish random(){
       return service.random();

    }

    @GET
    public List<Fish> findAll(){
       return this.service.findAll();
    }

    @POST
    public Fish insert(Fish fish) {
        fish.id = null;
        return this.service.insert(fish);
    }

    @PUT
    @Path("{id}")
    public Fish update(@PathParam("id") String id, Fish fish){
       return this.service.update(id, fish)
               .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND));
    }

    @DELETE
    @Path("{id}")
    public void delete(@PathParam("id") String id){
        this.service.delete(id);
    }
}


In this example, we've created the FishResource class annotated with @Path("/fishes") to specify the base path for the RESTful API endpoints. We've injected the FishService using @Inject annotation.

The FishResource class provides various methods to handle different HTTP operations on the Fish entities. We have implemented methods for finding a Fish entity by ID, generating a random Fish entity, finding all Fish entities, inserting a new Fish entity, updating a Fish entity by ID, and deleting a Fish entity by ID.

The methods are annotated with appropriate JAX-RS annotations such as @GET, @POST, @PUT, and @DELETE, specifying the respective HTTP methods for each endpoint. We've also specified the media type as MediaType.APPLICATION_JSON to indicate that the API endpoints consume and produce JSON.

With FishResource in place, we now have a fully functional RESTful API interacting with the Fish entities. You can test the endpoints using cURL, Postman, or REST client tools.

Step 6: Testing Functionality

Now that we have implemented FishResource with the RESTful API endpoints, let's test the functionality using cURL commands in the terminal. Follow the steps below:

Make sure your Quarkus application is running. If not, start it using the following command:

Shell
 
./mvnw compile quarkus:dev


Open a new terminal window and use the following cURL commands to interact with the API:

Insert a Fish:

Shell
 
curl -X POST -H "Content-Type: application/json" -d '{"name": "Nemo", "color": "Orange"}' http://localhost:8080/fishes


Retrieve all Fishes:

Shell
 
curl http://localhost:8080/fishes


Retrieve a specific Fish by ID (replace <fish_id> with the actual ID of a Fish):

Shell
 
curl http://localhost:8080/fishes/<fish_id>


Update a Fish by ID (replace <fish_id> with the actual ID of a Fish):

Shell
 
curl -X PUT -H "Content-Type: application/json" -d '{"name": "Dory", "color": "Blue"}' http://localhost:8080/fishes/<fish_id>


Delete a Fish by ID (replace <fish_id> with the actual ID of a Fish):

Shell
 
curl -X DELETE http://localhost:8080/fishes/<fish_id>


Make sure to replace <fish_id> with the actual ID of a Fish you want to retrieve, update, or delete.

By executing these cURL commands, you can interact with the RESTful API and perform operations on the Fish entities in your MongoDB database.

Congratulations! You have successfully tested your application using cURL commands. You can now leverage these endpoints to manage Fish entities in your MongoDB database. Feel free to experiment further with different cURL commands and scenarios to explore the full potential of your application.

Conclusion

This article covers creating a sample application with MongoDB using Quarkus and Eclipse JNoSQL. We started by generating a Quarkus application with the necessary dependencies using the Quarkus starting code. We configured the MongoDB connection and created the Fish entity. We then implemented the FishService to handle the NoSQL database API and the FishResource to expose the functionality as RESTful API endpoints. Finally, we tested the application by interacting with the API using cURL commands.

Following this guide taught you how to build a robust application with MongoDB integration using Quarkus and Eclipse JNoSQL. You can extend and customize this application further to suit your needs and requirements. Happy coding!

Additional Resources

  • Quarkus JNoSQL integration
  • Sample code
Eclipse MongoDB Quarkus REST

Opinions expressed by DZone contributors are their own.

Related

  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Efficient Data Management With Offset and Cursor-Based Pagination in Modern Applications
  • Spring Boot Application With Spring REST and Spring Data MongoDB
  • CRUDing NoSQL Data With Quarkus, Part One: MongoDB

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!