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
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

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

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

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

  • Building a REST Application With Oracle NoSQL Using Helidon
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Micronaut vs Spring Boot: A Detailed Comparison
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example

Trending

  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • AI, ML, and Data Science: Shaping the Future of Automation
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Docker Model Runner: Streamlining AI Deployment for Developers
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Getting Started With Boot Spring 3.2.0: Building a Hello World REST API With NoSQL Integration

Getting Started With Boot Spring 3.2.0: Building a Hello World REST API With NoSQL Integration

In this tutorial, learn how to build a "Hello World" REST API integrated with HarperDB using Spring Boot 3.2.0.

By 
Otavio Santana user avatar
Otavio Santana
DZone Core CORE ·
Dec. 14, 23 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
6.3K Views

Join the DZone community and get the full member experience.

Join For Free

Embark on a journey into the latest advancements in Spring Boot development with version 3.2.0 as we guide you through creating a fundamental "Hello World" application. In this tutorial, our focus extends beyond the customary introduction to Spring; we delve into the intricacies of constructing a REST API while seamlessly integrating it with a NoSQL database. Spring Boot 3.2.0, with its array of new features and optimizations, sets the stage for an engaging exploration of contemporary development practices. This guide is tailored for both novices and seasoned developers, promising hands-on experience in harnessing the potential of Spring for robust, modern applications. Let's commence this journey into Spring 3.2.0, where simplicity meets innovation.

What’s New in Spring Boot 3.2.0

Spring Boot 3.2.0 represents a significant leap forward in Java development, demanding a minimum Java 17 environment and extending support to the cutting-edge Java 21. This version introduces many features that redefine the landscape of Spring framework usage.

One of the impressive features of Java is the support for virtual threads, which boosts scalability and responsiveness by utilizing lightweight threads. Furthermore, Spring Boot 3.2.0 introduces initial support for Project CRaC (JVM Checkpoint Restore), which enables applications to recover their state after a JVM restart, thus enhancing reliability and resilience.

Security takes center stage with SSL Bundle Reloading, enabling dynamic reloading of SSL bundles. This feature empowers developers to manage SSL certificates more dynamically, ensuring both agility and security in their applications.

Observability improvements are woven throughout the release, providing developers with enhanced monitoring and tracing capabilities for a more transparent and manageable development experience.

In line with modern development practices, Spring Boot 3.2.0 introduces dedicated clients for RESTful (RestClient) and JDBC (JdbcClient) operations. These additions streamline communication with external services, enhancing integration capabilities.

Compatibility with Jetty 12 is another noteworthy inclusion, allowing developers to leverage the latest features of the Jetty web server. Spring Boot 3.2.0 expands its ecosystem compatibility with support for Apache Pulsar, broadening the messaging capabilities of Spring for building robust, event-driven applications.

Acknowledging the prevalence of Kafka and RabbitMQ, Spring Boot 3.2.0 introduces SSL bundle support for these popular messaging systems, bolstering the security posture of applications relying on these message brokers.

The release also addresses dependency management intricacies with a reworked approach to handling nested JARs, ensuring more reliable and predictable application deployments. Lastly, Docker Image Building sees improvements, streamlining the containerization process and enhancing Spring applications' portability and deployment efficiency.

In conclusion, Spring Boot 3.2.0 aligns itself with the latest Java versions, introduces groundbreaking features, and refines existing capabilities. This release empowers developers to confidently build modern, resilient, and highly performant applications in the ever-evolving landscape of Java development.

Show Me the Code

In this session, we embark on an exciting journey to develop a Pokemon API, leveraging the power of Spring and integrating it seamlessly with HarperDB. Our focus will be on implementing fundamental CRUD (Create, Read, Update, Delete) operations, with a special emphasis on utilizing unique identifiers (IDs) for each Pokemon. By the end of this session, you’ll not only have a fully functional Spring application but also a Pokemon API at your disposal, ready to be extended and integrated into larger projects. Let’s dive into the world of Pokemon and Spring development, where simplicity meets innovation.

Ensure your NoSQL database, HarperDB, is up and running using Docker. Open your terminal and execute the following command:

Shell
 
docker run -d -e HDB_ADMIN_USERNAME=root -e HDB_ADMIN_PASSWORD=password -e HTTP_THREADS=4 -p 9925:9925 -p 9926:9926 harperdb/harperdb


This command pulls the HarperDB Docker image and starts a container with the specified configuration. The -p option maps the container’s ports to your local machine, making the HarperDB interface accessible at http://localhost:9925.

Head to the Spring Initializer to set up our Spring application. Follow these steps:

  1. Select the desired project settings (e.g., Maven or Gradle, Java version).
  2. Add dependencies: choose “Spring Web” from the dependencies list.
  3. Click “Generate” to download the project as a ZIP file.

Extract the downloaded ZIP file and import the project into your preferred Integrated Development Environment (IDE), such as IntelliJ IDEA or Eclipse.

Now that our Spring application is set up, the next crucial step is to integrate it with HarperDB. To achieve this, we must include the HarperDB dependency in our project. Add the following Maven dependency to your pom.xml file:

XML
 
<dependency>
    <groupId>io.harperdb</groupId>
    <artifactId>harpderdb-core</artifactId>
    <version>0.0.1</version>
</dependency>


With the dependency in place, let’s move on to the code. We’ll create a configuration class in Spring, HarperDB, to manage the connection and make it an integral part of the Spring Inversion of Control (IoC) container:

Java
 
@Configuration
public class HarperDB {

    @Bean
    public Template template() {
        Server server = ServerBuilder.of("http://localhost:9925")
                .withCredentials("root", "password");
        server.createDatabase("pokemons");
        server.createTable("pokemon").id("id").database("pokemons");
        return server.template("pokemons");
    }
}


This configuration class, annotated with @Configuration, creates a Spring bean named template. The Template object is a key component for interacting with HarperDB. We initialize it with the server connection details, including the server URL and login credentials. Additionally, we create a database named “pokemons” and a table named “pokemon” with an “id” column. It sets the stage for storing our Pokemon entities in HarperDB.

To enhance the demo, we’ll first create an immutable entity using Java’s record feature:

Java
 
public record Pokemon(String id, String name, String location) {
}


This simple Pokemon record class encapsulates the basic attributes of a Pokemon—its ID, name, and location—in an immutable manner.

Next, let’s establish communication with the database by creating the PokemonService to serve as a bridge to HarperDB:

Java
 
@Service
public class PokemonService {

    private final Template template;

    public PokemonService(Template template) {
        this.template = template;
    }

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

    public void save(Pokemon pokemon) {
        template.upsert(pokemon);
    }

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


The PokemonService class is a Spring service that handles basic operations related to Pokemon entities. It utilizes the Template object we configured earlier to interact with HarperDB. The findById method retrieves a Pokemon by its ID, saves adds, or updates a Pokemon, and deletes and removes it from the database.

Lastly, let’s create the PokemonController to expose these operations as REST endpoints:

Java
@RestController
public class PokemonController {

    private final PokemonService service;

    public PokemonController(PokemonService service) {
        this.service = service;
    }

    @GetMapping("/pokemons/{id}")
    Pokemon findById(@PathVariable String id) {
        return service.findById(id).orElseThrow(() -> new PokemonNotFoundException(id));
    }

    @PutMapping("/pokemons")
    Pokemon newPokemon(@RequestBody Pokemon pokemon) {
        service.save(pokemon);
        return pokemon;
    }

    @DeleteMapping("/pokemons/{id}")
    void deleteEmployee(@PathVariable String id) {
        service.delete(id);
    }
}


This PokemonController class is annotated with @RestController and defines three endpoints:

  • GET /pokemons/{id} retrieves a Pokemon by its ID.
  • PUT /pokemons creates a new Pokemon or updates an existing one.
  • DELETE /pokemons/{id} deletes a Pokemon by its ID.

The controller relies on the PokemonService to handle these operations, providing a clean separation of concerns in our Spring application.

With these components in place, our Pokemon API can perform basic CRUD operations using HarperDB. Feel free to test the endpoints and see the seamless integration of Spring with the NoSQL database in action!

Your Spring application, integrated with HarperDB and equipped with a Pokemon API, is now ready for testing and execution. Let’s explore some common scenarios using curl commands. Before proceeding, make sure your Spring application is running.

Create a Pokemon

Shell
 
   curl -X PUT -H "Content-Type: application/json" -d '{"id": "1", "name": "Pikachu", "location": "Forest"}' http://localhost:8080/pokemons


This command creates a new Pokemon with ID 1, the name Pikachu, and the location Forest.

Retrieve a Pokemon by ID

Shell
 
curl http://localhost:8080/pokemons/{id}


Replace {id} with the actual ID of the Pokemon you just created.

Update a Pokemon

Shell
 
   curl -X PUT -H "Content-Type: application/json" -d '{"id": "1", "name": "Raichu", "location": "Thunderstorm"}' http://localhost:8080/pokemons


This command updates the existing Pokemon with ID 1 to have the name Raichu and location Thunderstorm.

Delete a Pokemon by ID

Shell
 
curl -X DELETE http://localhost:8080/pokemons/{id}


Replace {id} with the actual ID of the Pokemon you want to delete.

These scenarios provide a comprehensive test of the basic CRUD operations in your Pokemon API, starting with creating a Pokemon. Adjust the commands as needed based on your specific use case and data. Happy testing!

Conclusion

In this tutorial, we harnessed the capabilities of Spring Boot 3.2.0 to craft a streamlined Pokemon API integrated seamlessly with HarperDB. The latest Spring version introduced key features, enhancing our ability to create resilient and scalable applications.

Utilizing immutable entities, Spring IoC and HarperDB, we demonstrated the simplicity of modern Java development. The demo code, available here, is a foundation for your projects, ready for customization.

For updates and in-depth insights, refer to the official Spring blog. May your Spring Boot and HarperDB journey be filled with innovation and coding joy! Happy coding!

API Database NoSQL REST Spring Boot

Opinions expressed by DZone contributors are their own.

Related

  • Building a REST Application With Oracle NoSQL Using Helidon
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Micronaut vs Spring Boot: A Detailed Comparison
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example

Partner Resources

×

Comments

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
  • [email protected]

Let's be friends: