Building a REST Application With Oracle NoSQL Using Helidon
Dive into effortlessly creating a RESTful API with Java using Helidon and Oracle NoSQL in a straightforward manner, perfect for beginners.
Join the DZone community and get the full member experience.
Join For FreeIn this tutorial, we will explore the seamless integration of Oracle NoSQL with Helidon, a cloud-native set of Java libraries for developing microservices. By leveraging Helidon’s capabilities and Oracle NoSQL, we can effortlessly create a robust and scalable RESTful API.
But before delving into the implementation details, let’s take a moment to understand the critical components involved.
Understanding Oracle NoSQL Database
Oracle NoSQL Database is a distributed key-value and document database developed by Oracle Corporation. It offers powerful transactional capabilities, horizontal scalability, and simplified administration, making it an ideal choice for applications requiring low-latency access to data, flexible data models, and elastic scaling.
The Oracle NoSQL Database Cloud Service further simplifies deployment by providing a managed cloud platform, making it accessible and convenient for developers.
Introduction to Helidon
Helidon, on the other hand, is an open-source Java framework explicitly designed for building microservices. It provides a fast web core powered by Java virtual threads. It includes essential components such as CDI (Contexts and Dependency Injection), JSONP (JSON Processing), and JAX-RS (Java API for RESTful Web Services), which are crucial for building RESTful APIs.
Getting Started
This tutorial will kickstart our project by creating a Helidon MicroProfile (MP) application integrated with Eclipse JNoSQL to handle a Beer entity REST API. Helidon’s intuitive UI interface makes setting up a new project easy, and with Eclipse JNoSQL’s seamless integration, managing NoSQL databases becomes a breeze.
Creating the Project
Let’s begin by setting up our Helidon project using the Helidon Starter UI:
- Navigate to the Helidon Starter UI: Helidon Starter
- Select “Helidon MP” as the project type to leverage MicroProfile features.
- Choose “Quickstart” to generate a basic project template.
- For the JSON library, select “JSON-binding” to handle JSON serialization and deserialization.
- Define the
groupId
,artifactId
,version
, andpackage name
according to your preferences. Feel free to get creative with the naming!
Once configuring these settings, click “Generate Project” to download the project zip file.
Before diving into coding, let’s ensure everything is set up correctly. Follow these steps to ensure a smooth development experience:
Start Oracle NoSQL Database
Ensure that you have an Oracle NoSQL instance running. You can choose either the “primes” or “cloud” flavor. You can use Docker to run Oracle NoSQL in a container for local development. Use the following command:
docker run -d --name oracle-instance -p 8080:8080 ghcr.io/oracle/nosql:latest-ce
Maven Dependency
In your Maven project, include JNoSQL as a dependency in your pom.xml
file:
<dependency>
<groupId>org.eclipse.jnosql.databases</groupId>
<artifactId>jnosql-oracle-nosql</artifactId>
<version>${jnosql.version}</version>
</dependency>
Make sure to replace ${jnosql.version}
with the appropriate version of JNoSQL.
Configure Oracle NoSQL
Ensure that your application’s configuration matches the Oracle NoSQL setup. You can specify the configuration in your application.properties
file or any other configuration mechanism provided by Helidon. Here’s an example configuration:
# Oracle NoSQL Configuration
jnosql.keyvalue.database=beers
jnosql.document.database=beers
jnosql.oracle.nosql.host=http://localhost:8080
Adjust the jnosql.keyvalue.database
and jnosql.document.database
properties according to your application’s requirements. The jnosql.oracle.nosql.host
property should point to the host where Oracle NoSQL is running; in this case, http://localhost:8080
.
With these configurations in place, you’re all set to develop your Helidon application integrated with Oracle NoSQL using Eclipse JNoSQL. You can implement your RESTful API endpoints and seamlessly interact with the Oracle NoSQL database.
Now that we have defined our entities, repository, and resource classes, let’s integrate them into our Helidon project. Here’s how you can proceed:
Move the Beer Entity
Create a new Java class named Beer
in your Helidon project and copy the contents of the Beer
class from the previous project. Ensure you annotate the class with @Entity
and @JsonbVisibility(FieldAccessStrategy.class)
for JSON binding.
@Entity
@JsonbVisibility(FieldAccessStrategy.class)
public class Beer {
@Id
private String id;
@Column
private String style;
@Column
private String hop;
@Column
private String malt;
@Column
private List<String> comments;
}
Define the Beer Repository
Next, create a new Java interface named BeerRepository
in your Helidon project and copy the contents of the BeerRepository
interface from the previous project.
public interface BeerRepository extends Repository<Beer, String> {
Set<Beer> findByStyle(String style);
@Query("select * from Beer")
Set<Beer> query();
}
Implement the Beer Resource
Ensure you place this class within the appropriate package in your Helidon project. This class defines the RESTful endpoints for managing Beer entities and interacts with the BeerRepository to perform CRUD operations.
@Path("/beers")
@RequestScoped
public class BeerResource {
@Inject
private BeerRepository beerRepository;
@GET
public void getBeers(ServerRequest request, ServerResponse response) {
Multi<Beer> beers = beerRepository.findAll();
response.send(beers.collectList().map(Json::createArrayBuilder).map(JsonObject::build));
}
@GET
@Path("{id}")
public void getBeerById(@PathParam("id") String id, ServerRequest request, ServerResponse response) {
beerRepository.findById(id)
.onItem().ifNotNull().apply(response::send)
.onItem().ifNull().failWith(Http.Status.NOT_FOUND_404);
}
@PUT
public void insertBeer(ServerRequest request, ServerResponse response) {
request.content().as(JsonObject.class)
.thenApply(beerRepository::save)
.thenApply(unused -> response.send());
}
@DELETE
@Path("{id}")
public void deleteBeer(@PathParam("id") String id, ServerRequest request, ServerResponse response) {
beerRepository.deleteById(id)
.thenApply(unused -> response.status(Http.Status.NO_CONTENT_204).send());
}
}
Packaging and Running the Application
After implementing the BeerResource
class and ensuring everything is set up correctly, you can package and run your Helidon application. Here are the steps:
Package the Application
Execute the following Maven command to package your Helidon application:
mvn package
Run the Application
Once the packaging is complete, you can run your Helidon application using the generated JAR file. Use the following command:
java -jar target/helidon.jar
This command starts the Helidon server and deploys your application.
Interacting With the API
Now that your Helidon application is running, you can interact with the Beer API using curl
commands. Here’s how:
Get All Beers
curl -X GET http://localhost:8181/beers
Get a Specific Beer by ID
curl -X GET http://localhost:8181/beers
Replace <beer_id>
with the actual ID of the beer you want to retrieve.
Insert a New Beer
curl --location --request PUT 'http://localhost:8181/beers' \
--header 'Content-Type: application/json' \
--data '{"style":"IPA", "hop":"Cascade", "malt":"Pale Ale", "comments":["Great beer!", "Highly recommended."]}'
Delete a Beer by ID
curl -X DELETE http://localhost:8181/beers/<beer_id>
Replace <beer_id>
with the actual ID of the beer you want to delete.
By following these steps and executing the provided curl
commands, you can effectively test the functionality of your Beer API endpoints and ensure that they interact correctly with the Oracle NoSQL database.
Conclusion
In this tutorial, we have successfully integrated Oracle NoSQL with Helidon to build a RESTful API for managing Beer entities. By leveraging Helidon’s lightweight framework and Eclipse JNoSQL’s seamless integration, we have demonstrated how easy it is to develop microservices that interact with NoSQL databases.
We began by setting up a Helidon project using the Helidon Starter UI and configuring dependencies for Helidon MP and Eclipse JNoSQL. We then migrated our entities, repository, and resource classes from a previous Java SE project into the Helidon project, ensuring proper annotations and configurations were applied.
After packaging and running our Helidon application, we tested the Beer API endpoints using curl
commands to interact with the Oracle NoSQL database seamlessly.
This tutorial provides a solid foundation for building modern cloud-native applications with Helidon and Oracle NoSQL. For further exploration and reference, the complete project generated from this tutorial can be found at the following GitHub repository: test-helidon.
By leveraging Helidon and Oracle NoSQL, developers can create scalable, efficient, and resilient microservices that meet the demands of today’s distributed systems.
Feel free to explore the project, experiment with additional features, and adapt it to suit your specific use cases and requirements. Happy coding!
Opinions expressed by DZone contributors are their own.
Comments