Spring Boot simplifies integrating MySQL into your Java applications. Follow this guide to set up a database connection and perform CRUD operations with JPA.

Step-by-Step Setup

1. Add Dependencies 📦

Include MySQL Connector and Spring Data JPA in your pom.xml:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Spring Boot

2. Configure Database Connection 🗄️

Update application.properties with your MySQL details:

spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
MySQL

3. Create Entity Class 🐰

Define a JPA entity for your database table:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    // Getters and setters
}

4. Build Repository Interface 📁

Create a repository interface extending JpaRepository:

public interface UserRepository extends JpaRepository<User, Long> {
    // Custom query methods
}

5. Test Connection 🧪

Use @SpringBootTest to verify database connectivity:

@SpringBootTest
public class DatabaseTest {
    @Autowired
    private UserRepository userRepo;
    
    @Test
    public void testConnection() {
        userRepo.save(new User("John", "john@example.com"));
        assertNotNull(userRepo.findById(1L).orElse(null));
    }
}

Additional Resources 📚

For visual guides, check out:

Spring Data JPA
MySQL Database