Integrating MySQL and Spring Boot [Java Spring Boot Mastery Series – Part 8]
To use MySQL with Spring Boot, you’ll configure the database connection, define entities, and use Spring Data JPA repositories.
🧰 1. Add MySQL & JPA Dependencies (Maven)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
Description:
spring-boot-starter-data-jpaadds Hibernate and Spring Data support.mysql-connector-javais the JDBC driver for MySQL.
⚙️ 2. Configure application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/myappdb
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
Description:
ddl-auto=updatecreates or updates tables based on entities.show-sql=truelogs SQL statements.MySQL8Dialectenables support for MySQL 8 features.
🧱 3. Define Entity Example
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// Getters and Setters
}
Description:
@Entitymarks the class as a JPA entity.@Id+@GeneratedValuesets up the primary key auto-increment strategy.
📦 4. Repository Interface
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByNameContainingIgnoreCase(String keyword);
}
🧪 5. Load Sample Data (Optional)
Use CommandLineRunner to pre-populate the database:
@Bean
CommandLineRunner runner(ProductRepository repo) {
return args -> {
repo.save(new Product("Laptop", 699.99));
repo.save(new Product("Mouse", 29.99));
};
}
✅ 6. Test With API (Optional)
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductRepository repository;
@GetMapping
public List<Product> getAll() {
return repository.findAll();
}
}
➡️ Next Up: Part 9 – Swagger Integration for API Documentation
