jav spring boot mastery

Getting Started with Spring Boot [Java Spring Boot Mastery Series – Part 1]

🎯 Objective

Learn how to:

  • Set up a Spring Boot project from scratch
  • Connect to MySQL database
  • Run a basic REST API endpoint

🛠️ Step 1: Project Setup (Using Spring Initializr)

Go to https://start.spring.io and choose:

  • Project: Maven (build automation tool).
  • Language: Java
  • Spring Boot: 3.x.x (latest stable version).
  • Dependencies:
    • Spring Web: To build web and RESTful applications.
    • Spring Data JPA: ORM support for working with relational databases.
    • MySQL Driver: JDBC driver to connect to MySQL.
    • Spring Boot DevTools: Enables hot-reloading.
  • Packaging: JAR (Java Archive).
  • Java: 17+ (LTS version preferred).

Click Generate to download the project and extract it locally.

📁 Step 2: Directory Structure

src/main/java/com/example/demo
├── controller # REST endpoints
├── service # Business logic
├── repository # Data access layer
├── model # JPA entities (tables)
└── DemoApplication.java # Main class to run app

⚙️ Step 3: MySQL Configuration

Update src/main/resources/application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/demo_db
spring.datasource.username=root
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

🔍 Breakdown

  • spring.datasource.url: Connection URL for your MySQL DB.
  • ddl-auto=update: Auto-creates/updates tables based on entities.
  • show-sql=true: Logs the executed SQL queries.
  • dialect: Tells Hibernate which SQL syntax to use.

🧱 Step 4: Define Entity

@Entity
public class Employee {

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

    private String name;
    private String email;

    // Getters & Setters
}

🔍 Explanation

  • @Entity: Maps this class to a table named employee.
  • @Id: Specifies id is the primary key.
  • @GeneratedValue: Auto-generates ID (MySQL auto_increment).
  • GenerationType.IDENTITY: Uses DB identity column for generation.

📦 Step 5: Create the Repository Interface

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}

🔍 Explanation

  • JpaRepository<T, ID>: Inherits CRUD methods like save(), findAll().
  • @Repository: Optional, but useful for exception translation.

⚙️ Step 6: Build the Service Layer

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    public List<Employee> getAllEmployees() {
        return employeeRepository.findAll();
    }

    public Employee save(Employee emp) {
        return employeeRepository.save(emp);
    }
}

🔍 Explanation

  • @Service: Marks it as a service component.
  • @Autowired: Injects repository dependency automatically.
  • findAll(): Returns all records.
  • save(): Saves/updates a record.

🌐 Step 7: Create the REST Controller

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping
    public List<Employee> getAll() {
        return employeeService.getAllEmployees();
    }

    @PostMapping
    public Employee create(@RequestBody Employee emp) {
        return employeeService.save(emp);
    }
}

🔍 Explanation

  • @RestController: Handles web requests and returns JSON.
  • @RequestMapping("/api/employees"): Prefix for all endpoints.
  • @GetMapping: Maps HTTP GET to method.
  • @PostMapping: Accepts JSON payload to create record.
  • @RequestBody: Deserializes incoming JSON into Java object.

▶️ Step 8: Running the Application

🔍 Explanation

  • @SpringBootApplication: Shortcut for @Configuration, @EnableAutoConfiguration, and @ComponentScan.
  • SpringApplication.run: Bootstraps the application.

Test in Postman:

  • GET http://localhost:8080/api/employees
  • POST http://localhost:8080/api/employees
{
  "name": "Ved",
  "email": "[email protected]"
}

Congratulations! You have created and tested your first full-stack Spring Boot application using MySQL.

➡️ Next Up: Part 2 – Spring Boot Starters, Auto-Configuration and Dependency Injection

Similar Posts