This project is a simple API developed using Spring Boot, designed for educational purposes. The API connects to a MySQL database to perform CRUD (Create, Read, Update, Delete) operations on a Person entity.
- CRUD Operations: Create, retrieve, update, and delete
Personrecords in the database. - Validation: Ensures that the
Personentity has valid data before performing operations. - Custom Queries: Includes custom repository methods for specific data retrieval needs.
- Java 17: Ensure that Java 17 is installed on your machine.
- Maven: Required for building and managing the project dependencies.
- MySQL Database: Set up a MySQL database to connect with the application.
-
Clone the Repository:
git clone https://github.com/buenolas/api-spring.git
-
Configure the Database:
Update the
application.propertiesfile located insrc/main/resources/with your MySQL database credentials:spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name spring.datasource.username=your_username spring.datasource.password=your_password spring.jpa.hibernate.ddl-auto=update
-
Build the Project:
Navigate to the project directory and run:
mvn clean install
-
Run the Application:
Start the Spring Boot application using:
mvn spring-boot:run
-
Access the API:
The API will be accessible at
http://localhost:8080.
-
Create a Person
- POST
/api - Request Body:
{ "name": "John Doe", "age": 30 }
- POST
-
Get All Persons
- GET
/api
- GET
-
Get Person by ID
- GET
/api/{id}
- GET
-
Update Person
- PUT
/api/{id} - Request Body:
{ "name": "Jane Doe", "age": 25 }
- PUT
-
Delete Person
- DELETE
/api/{id}
- DELETE
-
Count Total Persons
- GET
/api/count
- GET
-
Order Persons by Name
- GET
/api/orderName
- GET
-
Order Persons by Age
- GET
/api/orderAge
- GET
-
Order Persons by Name and Age
- GET
/api/orderNameAge
- GET
-
Search Persons Containing Name
- GET
/search/containing/{term} - Path Variable:
term(the term to search for)
- GET
-
Sum of All Ages
- GET
/api/sumAges
- GET
-
Search Persons by Age or Higher
- GET
/search/ages/{age} - Path Variable:
age(the minimum age to search for)
- GET
The Repository interface extends CrudRepository and includes custom methods:
List<Person> findByOrderByName();List<Person> findByOrderByAge();List<Person> findByNameOrderByAgeDesc(String name);List<Person> findByNameContaining(String word);@Query("SELECT SUM(age) FROM persons") int sumAges();@Query("SELECT * FROM persons WHERE age >= :age") List<Person> searchAgeOrHigher(int age);
The service layer includes validation to handle errors gracefully, returning appropriate HTTP status codes and messages for invalid inputs or operations.
This project is licensed under the MIT License.
This project is inspired by the need to understand Spring Boot and its integration with MySQL for building RESTful APIs.
For more information, visit the Spring Boot Documentation.