Exploring the World of Web Development Part 5 - Spring and MySQL database

In today's digital age, data plays a crucial role in web applications. Storing and retrieving data efficiently is essential for the success of any web development project. One of the most popular and widely used databases for web applications is MySQL. In this article, we will explore how to configure Spring Boot with MySQL, learn how to save and retrieve data, and understand the process of altering and removing data. This tutorial is designed for beginners in web development, and it is recommended to continue using the code from the previous articles to build upon the existing Spring project.

Configuring Spring Boot with MySQL

To begin, let's ensure that our Spring project is configured to work with MySQL. If you haven't set up a local MySQL database yet, you can download the installer from mysql.com and follow the installation steps. Once installed, set up your credentials, including a username and password, and create a new database for your application. If you want to read MySQL installation on Windows, refer to this article.

After you have MySQL running, you can try to login using cmd and try to create a new database for this project.

mysql -u root -p
create database TestDB;

Next, open your existing Spring project. If you don't have one, you can clone the project from the GitHub repository located at mudiadamz/backend-department-store

Now, add the MySQL library to your project's pom.xml file to enable MySQL integration. This step ensures that your application can communicate with the MySQL database.

After adding the library, open the application.yaml (or application.properties) file in your project and configure the username, password, and database name to match your local MySQL database. This step establishes the connection between your Spring application and the MySQL database.

Model and Repository Integration

Since we have already implemented the product model in a previous article, we can focus on integrating the repository with the database. In Spring, the repository, or specifically the Spring Data Repository, is responsible for handling storage, retrieval, filtering, sorting, paging, searching, updating, and deleting operations.

The model represents the table in the database, while the repository provides the implementation for interacting with the database. By linking the model and repository, we can seamlessly integrate database operations into our Spring application. 

In our repository we don’t have to create our own save, update and delete  mechanism because it is already provided by Spring JPA. We only need to implement findByNameContainingIgnoreCase() to get a list of products with filtering, paging and sorting.

API Development

In the Part 4 tutorial, we created a bare minimum API to retrieve a list of products without any filtering. Now, we need to enhance our API by adding more functionality for product management. We will implement features such as storing, paging, sorting, retrieving a single product's details, and updating product information such as price, photos, and descriptions.

To achieve this, we update our new implementations in the repository, next we have to invoke them in our service layer. The repository will handle the underlying database operations, while the service layer acts as an intermediary between the repository and the controllers.

Now we can call our service that implements filtering, sorting and paging from our Controller.

Let's create a new endpoint to handle the submission of a new product using our product service. This controller will receive the necessary information for creating a new product and pass it to the service layer, which, in turn, will interact with the repository to store the data in the MySQL database.

And then our product Data Transfer Object (DTO).

DTOs serve as containers for data that needs to be transferred across boundaries, such as between the frontend and backend or between different microservices in a distributed system. In this example, the ProductRequest is a DTO class representing the request body for creating or updating a product. It includes fields such as name and price, which can be customized based on your product's attributes.

In addition to the creation controller, we will also create a separate endpoint for retrieving a product's details, updating a product's information, and deleting a product. These controllers will interact with the service layer, which will perform the necessary operations using the repository.

And then create another endpoint for updating a product, deleting a product and  getting a single product detail.

Congratulations! Our API now includes all the essential features of a CRUD (Create, Read, Update, Delete) system. However, it's important to note that most APIs on the internet implement additional restrictions, such as allowing only registered users to create a product or permitting only the user who created a product to modify it.

Testing Our New API

Testing your endpoints in Postman is one easy way to ensure the API is functioning correctly and returning the expected results. Here's a general set up of how you can test your endpoints using Postman.

Make sure the response you get is HTTP 200 success. Try different Scenarios by using Postman  by modifying the request parameters, headers, or body. See if you can test error responses, pagination, sorting, or different input values to ensure your API handles them correctly.

Front end integration

In the second series, we manage to create a bare minimum static html page without calling the data from an API. Now in the front end side, we have to create a new HTML page for listing products, create a searching box, create a sorting button, create paging and a hyperlink for each product when it clicks it gets to another page showing the product detail. But we will cover that in the next tutorial.

User Authentication

After that, we will also address the need for user authentication in our REST API and create an Admin Panel complete with admin login and a feature to manage our product. User authentication is a crucial security measure that ensures only authorized individuals can access certain features or perform specific actions within an application, for example only authorized users can manage our product. By implementing user authentication, we can add an extra layer of protection to our API, restrict access to sensitive operations, and provide a personalized experience for users. 

Stay tuned for the next article, where we will delve into user authentication and integrate it into our Spring application. Also you may need to check the previous article of this web development series for the source code of our front end, and consider following our social media account so you will get a notification when the next article arrives.

Conclusion

In this article, we explored the world of web development by focusing on Spring and MySQL database integration. We learned how to configure Spring Boot with MySQL, integrate the model and repository for database operations, and develop APIs for product management. By following the step-by-step instructions, we successfully implemented a feature-rich API capable of creating, reading, updating, and deleting products.

However, we also acknowledged the importance of user authentication in securing our API and enhancing the user experience. In the next article, we will dive deeper into user authentication and explore how to incorporate it into our REST API.

Web development is an ever-evolving field, and mastering the integration of different technologies and databases is essential for building robust and scalable applications. By exploring the world of web development, you are equipping yourself with the skills and knowledge necessary to create innovative and impactful web applications.

Keep exploring, keep learning, and stay tuned for the next installment in this series as we continue our journey into the exciting realm of web development!

Read the previous chapter:


Popular posts from this blog

Spring Kafka - how to use ReplyingKafkaTemplate send and reply synchronously

ERROR 1348 Column Password Is Not Updatable When Updating MySQL Root Password

Intellij Error: Spring class file has wrong version 61.0, should be 55.0

How To Create Spring Boot Project Using Netbeans

How To Use React Ckeditor Upload File Image With Demo and Example Codes