Hackforge Academy

Category: spring_boot

Spring Boot REST API to a MySQL database

Published on 26 Jun 2026

Explanation

To connect a Spring Boot REST API to a MySQL database, first configure the database connection properties in the application.properties file. Spring Boot uses these settings to establish a connection with MySQL.

Code:

spring.datasource.url=jdbc:mysql://
localhost:3306/studentdb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Explanation

Create an Entity class to map a Java object to a database table. The @Entity annotation marks the class as a JPA entity, and @Id identifies the primary key column.

Code:

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = 
GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    // Getters and Setters
}

Explanation

Create a Repository interface to perform database operations. Spring Data JPA automatically provides implementations for common CRUD operations.

Code:

import org.springframework.data.jpa.
repository.JpaRepository;

public interface StudentRepository
 extends JpaRepository<Student, Long> {
}

Explanation

Use the repository inside a REST controller to fetch and store data in the MySQL database. Dependency injection is handled using the @Autowired annotation.

Code:

@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentRepository repository;

    @GetMapping
    public List<Student> getStudents() {
        return repository.findAll();
    }
}

Explanation

Create new records in the database using a POST API. The incoming JSON request is converted into a Student object and saved using the repository.

Code:

@PostMapping
public Student createStudent(
@RequestBody Student student) {
    return repository.save(student);
}

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community