Skip to content

Latest commit

 

History

History
489 lines (355 loc) · 11.6 KB

File metadata and controls

489 lines (355 loc) · 11.6 KB

Getting Started Guide

Quick Start: Get your first Spring Boot API running in under 10 minutes!

This guide will walk you through setting up the Java Spring Boot boilerplate and creating your first REST API endpoint.

Prerequisites Check

Before starting, verify you have:

# Check Java version (must be 21+)
java -version

# Check Maven version (must be 3.8+)
mvn -version

# Check Git is installed
git --version

If any are missing, see the Prerequisites section for installation links.

Step 1: Clone and Setup (2 minutes)

Clone the Repository

# Clone the repository
git clone [repository-url]
cd backend-java-spring-boot

# Verify project structure
ls -la

You should see directories like docs/, standards/, rules/, and eventually src/.

Install Dependencies

# Build the project (this will download all dependencies)
mvn clean install -DskipTests

# This may take a few minutes on first run

Step 2: Configure the Application (2 minutes)

Option A: Use H2 In-Memory Database (Easiest)

For quick testing, use H2 (no PostgreSQL required):

Create src/main/resources/application-dev.yml:

spring:
  application:
    name: spring-boot-api

  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    username: sa
    password:

  h2:
    console:
      enabled: true
      path: /h2-console

  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: create-drop
    show-sql: true

server:
  port: 8080

logging:
  level:
    root: INFO
    com.example: DEBUG

Option B: Use PostgreSQL (Production-like)

If you have PostgreSQL installed:

  1. Create a database:
psql -U postgres
CREATE DATABASE springbootdb;
\q
  1. Create src/main/resources/application-dev.yml:
spring:
  application:
    name: spring-boot-api

  datasource:
    url: jdbc:postgresql://localhost:5432/springbootdb
    username: postgres
    password: your_password
    driver-class-name: org.postgresql.Driver

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect

server:
  port: 8080

logging:
  level:
    root: INFO
    com.example: DEBUG

Step 3: Create Your First Entity (3 minutes)

Create a simple User entity:

File: src/main/java/com/example/demo/model/entity/User.java

package com.example.demo.model.entity;

import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;

@Entity
@Table(name = "users")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {

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

    @Column(nullable = false, unique = true, length = 100)
    private String email;

    @Column(nullable = false, length = 100)
    private String name;

    @Column(nullable = false)
    @Builder.Default
    private Boolean active = true;

    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private LocalDateTime createdAt;

    @UpdateTimestamp
    @Column(nullable = false)
    private LocalDateTime updatedAt;
}

Step 4: Create a Repository (1 minute)

File: src/main/java/com/example/demo/repository/UserRepository.java

package com.example.demo.repository;

import com.example.demo.model.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findByEmail(String email);

    boolean existsByEmail(String email);
}

Step 5: Create a Service (2 minutes)

File: src/main/java/com/example/demo/service/UserService.java

package com.example.demo.service;

import com.example.demo.model.entity.User;
import com.example.demo.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;

    @Transactional(readOnly = true)
    public List<User> findAll() {
        log.debug("Finding all users");
        return userRepository.findAll();
    }

    @Transactional(readOnly = true)
    public Optional<User> findById(Long id) {
        log.debug("Finding user by id: {}", id);
        return userRepository.findById(id);
    }

    @Transactional
    public User createUser(User user) {
        log.info("Creating new user: {}", user.getEmail());

        if (userRepository.existsByEmail(user.getEmail())) {
            throw new IllegalArgumentException("Email already exists: " + user.getEmail());
        }

        return userRepository.save(user);
    }

    @Transactional
    public User updateUser(Long id, User userDetails) {
        log.info("Updating user: {}", id);

        User user = userRepository.findById(id)
            .orElseThrow(() -> new IllegalArgumentException("User not found: " + id));

        user.setName(userDetails.getName());
        user.setEmail(userDetails.getEmail());
        user.setActive(userDetails.getActive());

        return userRepository.save(user);
    }

    @Transactional
    public void deleteUser(Long id) {
        log.info("Deleting user: {}", id);

        if (!userRepository.existsById(id)) {
            throw new IllegalArgumentException("User not found: " + id);
        }

        userRepository.deleteById(id);
    }
}

Step 6: Create a REST Controller (3 minutes)

File: src/main/java/com/example/demo/controller/UserController.java

package com.example.demo.controller;

import com.example.demo.model.entity.User;
import com.example.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = userService.findAll();
        return ResponseEntity.ok(users);
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return userService.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        User createdUser = userService.createUser(user);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        User updatedUser = userService.updateUser(id, user);
        return ResponseEntity.ok(updatedUser);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}

Step 7: Create Main Application Class

File: src/main/java/com/example/demo/DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Step 8: Run Your Application (1 minute)

# Run with dev profile
mvn spring-boot:run -Dspring-boot.run.profiles=dev

You should see output like:

Started DemoApplication in 3.456 seconds

Step 9: Test Your API (2 minutes)

Using cURL

Create a user:

curl -X POST http://localhost:8080/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "active": true
  }'

Get all users:

curl http://localhost:8080/api/v1/users

Get user by ID:

curl http://localhost:8080/api/v1/users/1

Update a user:

curl -X PUT http://localhost:8080/api/v1/users/1 \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Smith",
    "email": "john.smith@example.com",
    "active": true
  }'

Delete a user:

curl -X DELETE http://localhost:8080/api/v1/users/1

Using Browser or Postman

Success! What's Next?

Congratulations! You've created your first Spring Boot REST API. Here's what to explore next:

Immediate Next Steps

  1. Add Validation - Add @Valid and Bean Validation annotations

  2. Add Exception Handling - Create a @RestControllerAdvice for global error handling

  3. Add DTOs - Separate internal entities from API contracts

  4. Add Tests - Write unit and integration tests

Explore Advanced Features

Troubleshooting

Port Already in Use

# Change port in application-dev.yml
server:
  port: 8081

Database Connection Error

Build Failures

# Clean and rebuild
mvn clean install

# Check Java version
java -version  # Must be 21+

Class Not Found Errors

  • Ensure package names match in all files
  • Verify @SpringBootApplication is in the root package

Common Questions

Q: Can I use a different database? A: Yes! Spring Boot supports MySQL, MariaDB, Oracle, SQL Server, etc. Just change the dependency in pom.xml and update application-dev.yml.

Q: How do I add more endpoints? A: Create new @RestController classes following the same pattern as UserController.

Q: Where do I add business logic? A: In the service layer (@Service classes). Keep controllers thin.

Q: How do I secure my endpoints? A: Add Spring Security and JWT authentication. Security guide is planned for future implementation.

Resources


Next: Add Validation and DTOs | Coding Standards

Last Updated: 2025-10-14