Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring Boot - CRUD Operations

In Spring Boot, creating CRUD (Create, Read, Update, Delete) operations can be efficiently implemented using the Spring Data JPA, which provides methods to operate on the database directly without having to write the boilerplate CRUD code.

Here's a step-by-step guide to implement CRUD operations:

1. Setup Dependencies

Add Spring Data JPA and your preferred database driver to your pom.xml:

<!-- Spring Data JPA -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- H2 Database for demonstration -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

2. Configure Database

For the sake of simplicity, we'll use an in-memory H2 database:

src/main/resources/application.properties:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

# H2 console enabled for simplicity
spring.h2.console.enabled=true

3. Create Entity

Create a simple entity User:

@Entity
public class User {

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

    // Getters, Setters, Constructors, hashCode, equals, toString
}

4. Create Repository

Create a repository for the User entity:

public interface UserRepository extends JpaRepository<User, Long> {
}

5. Create Service

Service class abstracts the logic:

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    public User createUser(User user) {
        return userRepository.save(user);
    }

    public User updateUser(Long id, User user) {
        if (userRepository.existsById(id)) {
            user.setId(id);
            return userRepository.save(user);
        } else {
            return null;
        }
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

6. Create Controller

Now, let's create the RESTful API:

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

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        return userService.updateUser(id, user);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }
}

Now, you can run your Spring Boot application, and it will have the full CRUD operations available under the /users endpoint.

Remember, this is a basic CRUD setup. Depending on your needs, you might want to add error handling, validation, DTOs, pagination, etc.

  1. Implementing CRUD repository in Spring Boot:

    • Use Spring Data JPA to create a CRUD repository interface for the entity.
    • Example:
      public interface UserRepository extends CrudRepository<User, Long> {
          // Custom query methods if needed
      }
      
  2. Database operations with Spring Boot JPA CRUD repository:

    • Perform database operations by injecting and using the CRUD repository.
    • Example:
      @Service
      public class UserService {
          @Autowired
          private UserRepository userRepository;
      
          public List<User> getAllUsers() {
              return (List<User>) userRepository.findAll();
          }
      
          // Implement other CRUD operations
      }
      
  3. Using Spring Data REST for CRUD operations in Spring Boot:

    • Leverage Spring Data REST to automatically expose CRUD operations as RESTful APIs.
    • Example:
      @RepositoryRestResource(path = "users")
      public interface UserRepository extends JpaRepository<User, Long> {
          // Automatically exposes CRUD APIs at "/users"
      }
      
  4. Customizing CRUD operations in Spring Boot:

    • Customize RESTful endpoints and operations using annotations like @RequestMapping and @RestController.
    • Example:
      @RestController
      @RequestMapping("/api/users")
      public class UserController {
          // Implement custom CRUD operations
      }
      
  5. CRUD operations with Thymeleaf in Spring Boot:

    • Use Thymeleaf templates for server-side rendering in CRUD operations.
    • Example:
      @Controller
      public class UserController {
          @Autowired
          private UserService userService;
      
          @GetMapping("/users")
          public String getAllUsers(Model model) {
              model.addAttribute("users", userService.getAllUsers());
              return "userList";
          }
      }
      
  6. Validating input in Spring Boot CRUD operations:

    • Implement input validation using annotations like @Valid and @NotBlank.
    • Example:
      @PostMapping("/users")
      public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
          // Validate and create user
      }
      
  7. Handling exceptions in Spring Boot CRUD operations:

    • Implement exception handling to gracefully handle errors in CRUD operations.
    • Example:
      @ControllerAdvice
      public class GlobalExceptionHandler {
          @ExceptionHandler(Exception.class)
          public ResponseEntity<ErrorResponse> handleException(Exception ex) {
              // Handle and return custom error response
          }
      }