π We're going to walk through connecting your Spring Boot application to a MySQL database.
Before we start, make sure you have:
First, let's add the necessary dependencies to your build.gradle
file. These are like telling your application what tools it needs to work with MySQL.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'mysql:mysql-connector-java'
// Your other dependencies...
}
Now, let's tell your application how to find and connect to your MySQL database. Create or open src/main/resources/application.properties
and add these lines:
# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
# Hibernate Configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
Remember to replace:
your_database_name
with your actual database nameyour_username
with your MySQL usernameyour_password
with your MySQL passwordEntities are like blueprints for your database tables.
@Entity
@Table(name = "your_table_name")
@Data // If you're using Lombok
public class YourEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Add other fields as needed
}
Repositories help you interact with your database without writing SQL queries:
@Repository
public interface YourRepository extends JpaRepository<YourEntity, Long> {
// Spring Data JPA will implement this interface for you!
}
Let's create a simple test to make sure everything works:
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class YourRepositoryTest {
@Autowired
private YourRepository repository;
@Test
void testDatabaseConnection() {
// Your test code here
}
}
Connection Refused
Authentication Failed
Table Doesn't Exist
spring.jpa.hibernate.ddl-auto=update
is set