A simple Spring Boot application that demonstrates how to call a MySQL stored procedure from a Spring Data JPA repository.
This project exposes a REST API to fetch cars from the database using the stored procedure FIND_CARS_AFTER_YEAR.
- Creates a Spring Boot application with Spring Web and Spring Data JPA
- Connects to a MySQL database
- Calls a native SQL stored procedure via
@Query - Returns a list of
Carobjects filtered by year
- Java 17
- Spring Boot 2.7.5
- Spring Web
- Spring Data JPA
- MySQL Connector/J
- Maven
src/main/java/com/example/springbootandstoredprocedureSpringBootAndStoredProcedureApplication.java– application entry pointcontroller/CarController.java– REST controllerservice/CarService.java– business logic layerrepository/CarRepository.java– repository with stored procedure callentity/Car.java– entity mapped to thecartable
src/main/resources/application.properties– database and server configurationsrc/test/java/.../SpringBootAndStoredProcedureApplicationTests.java– basic Spring context test
Returns all cars whose model year is greater than the provided year.
Example:
curl http://localhost:6969/carsafteryear/2018The repository contains this native query:
@Query(value = "CALL FIND_CARS_AFTER_YEAR(:year_in);", nativeQuery = true)
List<Car> findCarsAfterYear(@Param("year_in") int year);This means the application depends on a MySQL stored procedure named FIND_CARS_AFTER_YEAR that accepts an input parameter year_in.
The current configuration is in src/main/resources/application.properties:
spring.jpa.show-sql=true
spring.jpa.defer-datasource-initialization=true
spring.datasource.url=jdbc:mysql://localhost:3306/practice_stored_procedure
spring.datasource.username=root
spring.datasource.password=password
server.port=6969- Install and start MySQL.
- Create a database named
practice_stored_procedure. - Create the
FIND_CARS_AFTER_YEARstored procedure. - Make sure the
cartable and its columns align with theCarentity.
From the project root:
cd Spring-Boot-and-Stored-Procedure
./mvnw spring-boot:runThe application will start on port 6969.
[
{
"id": 1,
"model": "Tesla Model 3",
"year": 2020
},
{
"id": 2,
"model": "BMW X5",
"year": 2022
}
]A basic application context test is included:
./mvnw test- The current code is focused on demonstrating stored procedure usage.
- The database schema and stored procedure are not included in the repository, so you need to create them in MySQL before running the app.
- The API currently exposes only one endpoint.
- Add SQL scripts for schema and stored procedure creation
- Add validation and error handling
- Add more CRUD endpoints
- Add integration tests for the API