jav spring boot mastery

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-jpa adds Hibernate and Spring Data support.
  • mysql-connector-java is 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=update creates or updates tables based on entities.
  • show-sql=true logs SQL statements.
  • MySQL8Dialect enables 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:

  • @Entity marks the class as a JPA entity.
  • @Id + @GeneratedValue sets 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

Similar Posts