This project implements a simple CRUD e-commerce API with an extendable data layer that supports both SQL (MySQL) and NoSQL (MongoDB) databases.
The problem we face is that when the service layer is tightly coupled with the data layer, it becomes difficult to maintain and develop the code. If you need to switch from an SQL to a NoSQL database (or vice versa), the code is not easily extendable to accommodate such changes.
To address this issue, we refactor the code to isolate the data layer from the service layer. This allows for the addition or change of databases by sending objects between layers that each knows how to handle, with the data layer converting these objects to the appropriate format for storage in SQL or NoSQL databases.
The architecture allows for easy extension of the data layer by adding any database.
Implementing multi-database support (SQL, NoSQL) in the data layer with different approaches:
- JOOQ With MySQL
- Spring Jdbc Template With MySQL
- Spring Data Jdbc With MySQL
- Spring Data JPA With
- MySQL
- MongoDB
In the service layer, to specify which database to use, you need to change the bean name to the corresponding data layer implementation. For example:
-
ProductServiceImpl.java Change the qualifier name to the appropriate database repository implementation:
@Autowired @Qualifier("mongoProductRepoImpl") <-------------- private ProductRepoInterface productRepo;
-
CategoryServiceImpl.java Follow the same step for the category repository:
@Autowired @Qualifier("mongoCategoryRepoImpl") <-------------- private CategoryRepoInterface categoryRepo;
-
Programming Languages
- Java 17
-
Databases
- MySQL 8
- MongoDB
-
Build Tool
- Maven
To run the application using Docker Compose, follow these steps:
-
Ensure Docker and Docker Compose are installed on your system. You can download Docker Desktop from Docker's official website.
-
Clone the repository if you haven't already:
git clone https://github.com/youssefGamalMohamed/spring-boot-database.git cd spring-boot-database
-
Build and run the Docker containers using Docker Compose:
docker-compose up --build
This command will build the Docker images and start the containers defined in the
docker-compose.yml
file. -
Access the application:
- The Spring Boot application should be available at
http://localhost:8080
by default.
- The Spring Boot application should be available at
-
Stop the Docker containers: To stop the running containers, use:
docker-compose down
- Download the Postman Collection from here